1. 程式人生 > >[Leetcode557] 反轉字串中的單詞 III

[Leetcode557] 反轉字串中的單詞 III

給定一個字串,你需要反轉字串中每個單詞的字元順序,同時仍保留空格和單詞的初始順序。 

python我用了函式內建的操作[::-1]翻轉。

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        return ' '.join([i[::-1] for i in s.split(' ')])

C++我沒有用標準庫reverse函式,而是用了兩個迭代去依次遍歷尋找單詞然後逐個單詞反轉。

class Solution {
public:
    string reverseWords(string s) {
        int i = 0;
        int j = 0;
        string res;
        while(j < s.length()){
            if(j != (s.length() - 1)){
                if(s[j] != ' ') j += 1;
                else{
                    for(int k = (j - 1);k >= i;k--) res += s[k];
                    res += ' ';
                    j += 1;
                    i = j;
                }
            }
            else if(i == j){
                res += s[i];
                break;
            }
            else{
                for(int k = j;k >= i;k--) res += s[k];
                break;
            }
        }
        return res;
    }
};