leetcode-557-Reverse Words in a String III

Topic description:

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.

 

Function to be done:

string reverseWords(string s) 

 

illustrate:

1. This problem is not difficult, find the position of the space, then reverse the word before the space, and process it until the last '\0' is encountered.

2. Consider the whole process, define two position indexes, one records the starting position i, and the other loops until a space is encountered, and records the position j before the space character. Then do a reversal between i and j, and implement it directly on the string.

j keeps looping, +1, until the next space character is encountered. Continue to do so.

Until the last j will not be less than the length of the string, then exit the loop and return to the original string.

code show as below:

    string reverseWords(string s) 
    {
        int i= 0 ,j= 0 ,t1;
         char t; // temporary variable for swapping letters 
        int s1= s.size();
         while (j< s1)
        {
            while(s[j]!=' '&&j<s1)
                j++;
            t1 =j+ 1 ; // where the next word starts 
            j--; // space before the character 
            while (i< j)
            {
                t=s[i];
                s[i]=s[j];
                s[j]=t;
                i++;
                j--;
            }
            i =t1; // update i to the first letter position of the next word 
            j=t1+ 1 ; // j is still in the next position of i 
        }
         return s;
    }

The above code measured 25ms, beats 52.53% of cpp submissions.

 

3. Improvement:

I saw someone using the reverse function in the discussion forum, and after testing it, it became beats 98.76%...

Also share with you, the code is as follows:

    string reverseWords(string s) 
    {
        int i=0,j=0,t1;
        char t;
        int s1=s.size();
        while(j<s1)
        {
            while(s[j]!=' '&&j<s1)
                j++;
            reverse(&s[i], &s[j]);
            i=j+1;//i更新到下一个单词的首位
            j=i+1;//j在i的下一位
        }
        return s;
    }

上述代码实测22ms,beats 98.76% of cpp submissions。

花费时间变少了,可能是因为reverse函数被优化了?笔者其实觉得2中的代码已经算是很高效的了,想不出有哪里还可以继续改进……希望知道怎么改进的同学不吝赐教。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325168669&siteId=291194637