zoukankan      html  css  js  c++  java
  • [LeetCOde] Reverse Words in a String III

     

    Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

    Example 1:

    Input: "Let's take LeetCode contest"
    Output: "s'teL ekat edoCteeL tsetnoc"

    Note: In the string, each word is separated by single space and there will not be any extra space in the string.

    题目要求把一个含有空格符的字符串中的每个单词反转,就需要对整个字符串根据空格符进行分割。对每个分割的单词进行反转,用tmp保存每个单词的首位索引,需要考虑的是最后一个单词后面没有空格,这时就对其进行单独判断后再进行反转。

    class Solution {
    public:
        string reverseWords(string s) {
            int count = 0, tmp = 0;
            for (int i = 0; i != s.size(); i++) {
                if (i == s.size() - 1) {
                    int left = tmp, right = i;
                    while (left <= right)
                        swap(s[left++], s[right--]);
                }
                else if (s[i] != ' ')
                    count = i;
                else {
                    int left = tmp, right = count;
                    while (left <= right)
                        swap(s[left++], s[right--]);
                    tmp = count + 2;
                    count += 1;
                }
            }
            return s;
        }
    };
    // 19 ms

    巧妙的写法:通过迭代器用i, j记录每个单词首末两位的偏移进行反转。

    class Solution {
    public:
        string reverseWords(string s) {
            for (int i = 0; i != s.size(); i++) {
                if (s[i] != ' ') {
                    int j = i;
                    for (; j != s.size() && s[j] != ' '; j++) {}
                    reverse(s.begin() + i, s.begin() + j);
                    i = j - 1;
                }
            }
            return s;
        }
    };
    // 23 ms

    python写法:'sep'.join(seq): 返回一个以分隔符sep连接各个元素后生成的字符串。 x[::-1]: 对每个字符串进行反转。 split(): 对整个字符串根据空字符进行分割。

    class Solution(object):
        def reverseWords(self, s):
            """
            :type s: str
            :rtype: str
            """
            return ' '.join(x[::-1] for x in s.split())
    # 82 ms
  • 相关阅读:
    ubuntu 安装 redis desktop manager
    ubuntu 升级内核
    Ubuntu 内核升级,导致无法正常启动
    spring mvc 上传文件,但是接收到文件后发现文件变大,且文件打不开(multipartfile)
    angular5 open modal
    POJ 1426 Find the Multiple(二维DP)
    POJ 3093 Margritas
    POJ 3260 The Fewest Coins
    POJ 1837 Balance(二维DP)
    POJ 1337 A Lazy Worker
  • 原文地址:https://www.cnblogs.com/immjc/p/7140774.html
Copyright © 2011-2022 走看看