557. Reverse Words in a String III

来源:互联网 发布:ubuntu mate 15.04 编辑:程序博客网 时间:2024/05/24 02:47

题目:

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.

思路:用空格来判断一个单词的结束和开始,用front(初始化为0) 来记录一个一个单词的开始,用i来找这个单词的结束,然后对这个单词进行反转操作;然后另front = i+1,再寻找下个单词,对这个单词进行反转操作,这样直到字符串的末尾。


代码;

class Solution {
public:
    string reverseWords(string s) {
        int size1 = s.size();
        int front = 0;
        for(int i = 0; i<=size1;i++)
        {
            if(i == size1 || s[i] == ' ')
            {
                for(int j = 0; j< (i-1 - front)/2;j++)
                {
                    char temp = s[front+j];
                    s[front+j] = s[i-1-j];
                    s[i-1-j] = temp;
                    
                    
                }
                front = i+1;
            }
        }
        return s;
        
    }
};

原创粉丝点击