• [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
  • 相关阅读:
    Thinphp+nginx配置伪静态
    Potyczki Algorythmiczne 2013
    接下来一段时间会对大家进行网络通信的魔鬼训练理解socket
    项目中怎样做技术选型
    面试官问我:你做事仔细吗?
    【编程一生】2021年总结数据可视化技巧
    一个反直觉的sql
    CURD系统怎么做出技术含量惊艳面试官
    深入理解函数式编程
    历史文章分类汇总
  • 原文地址:https://www.cnblogs.com/immjc/p/7140774.html
Copyright © 2020-2023  润新知