1. 程式人生 > >557. Reverse Words in a String III(python+cpp)

557. Reverse Words in a String III(python+cpp)

題目:

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.

解釋: 翻轉一個字串中的每個單詞。

python程式碼:

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        s_list=s.split(' ')
        result=[]
        for word in s_list:
            re_word=word[::-1]
            result.append(re_word)
        return " ".join(result)

c++程式碼:

class Solution {
public:
    string reverseWords(string s) {
        for(int i=0;i<s.length();i++)
        {
            if(s[i]!=' ')
            {
                int j=i;
                for(;j<s.length() &&s[j]!=' ';j++) {}
                reverse(s.begin()+i,s.begin()+j);
                //因為執行完這段程式以後需要i++,所以不能直接i=j
                i=j-1;
            }
        }
        return s;
        
    }
};

cpp中i在迴圈中是變化的,所以感覺用for迴圈不太合適,用while迴圈更合適一點。 c++第二種寫法:

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

總結: cpp直接是原地翻轉,注意reverse()的輸入也是左閉右開,不包括最後一個值。注意迴圈條件的判斷,感覺還是python更方便。