LeetCode_557_Reverse Words in a String III

Topic Description: Given a string, you need to flip the order of the character of each word in the string, while still need to retain the initial order of spaces and words.

输入示例:
输入: "Let's take LeetCode contest"
输出: "s'teL ekat edoCteeL tsetnoc"

1 thought (I thought): a character a character read and stored in the vector container, when the reading space, indicating that the first word has been read, then the reverse vector characters assigned back to the original character string can be.
Note: When reading the last word in the string, since there is no space at the end, so it needs to be dealt with separately last word, reverse the assignment back to the original string, with the former method of operation

class Solution {
public:
    string reverseWords(string s) {
        vector<char> store;
        int i;
        for(i=0;i<s.size();i++){
            if(s[i]!=' '){
                store.push_back(s[i]);
            }
            else{
                for(int j=0,p=i-1;j<store.size();j++){
                    s[p--]=store[j];
                }
                store.clear();
            }
        }
        for(int j=0,p=i-1;j<store.size();j++){
                    s[p--]=store[j];
                }
        return s;
    }
};

Time complexity of O (n), the spatial complexity of O (n)
the execution time as shown below:
The execution time of a train of thought

2 :( thinking individual ideas, the first use of python write LeetCode), with the same ideas 1, except that a few of the python function simplifies operation, but the running time of a lot slower, so just for reference only

class Solution(object):
    def reverseWords(self, s):
        """
        :type s: str
        :rtype: str
        """
        string=s.split()
        ans=""
        for line in string:
            line=list(line)
            line=line[::-1]
            line="".join(line)
            ans=ans+line+" "
        ans=ans.strip()
        return ans
        

Call python functions to achieve the same operation
To be continued ... To be continued ...

Guess you like

Origin blog.csdn.net/all_about_WZY/article/details/88170362