LeetCode151. 翻转字符串里的单词

给定一个字符串,逐个翻转字符串中的每个单词。

示例:  

输入: "the sky is blue",
输出: "blue is sky the".

说明:

  • 无空格字符构成一个单词。
  • 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
  • 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

题目分析:首先将原字符串逆转,然后挨个逆转连续的子串,特别要注意,多个空格在一起的情况。

代码展示:

class Solution {
public:
    void reverseWords(string &s){
        if(s.empty())
            return;
        reverse(s);
        string str = "";
        int i = 0;
        int j = 0;
        while(i<s.length()){
            while(s[i]==' '&&i<s.length())
                i += 1;
            if(i==s.length())
                break;
            j = i;
            while(s[j]!=' '&&j<s.length())
                j += 1;
            string temp = s.substr(i,j-i);
            reverse(temp);
            str += temp;
            str += " ";
            i = j;
        }
        s = str.substr(0,str.length()-1);
    }
    
    void reverse(string &s){
        char temp;
        for(int i=0;i<s.length()/2;i++){
            temp = s[i];
            s[i] = s[s.length()-i-1];
            s[s.length()-i-1] = temp;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/Jaster_wisdom/article/details/81410765
今日推荐