leetcode Online Judge 150題 解答分析之一 Reverse Words in a String

問題面試

Given an input string, reverse the string word by word.app

For example, Given s = "the sky is blue", return "blue is sky the".spa

面試時我應該至少問的問題blog

  1. What constitutes a word? A sequence of non-space characters constitutes a word.
  2. Could the input string contain leading or trailing spaces? Yes. However, your reversed string should not contain leading or trailing spaces.
  3. How about multiple spaces between two words? Reduce them to a single space in the reversed string.

 我大概想了下,可是沒有問出來,須要改進!ip

 

代碼分析字符串

class Solution {
public:
    static void reverseWords(string &s) 
    {
        int len = s.length();
        string result;
        for(int i= len - 1; i >= 0; )
        {
            int lastend = 0;
            while(i >= 0 && s[i] == ' ') //須要先判斷i >=0,不然s[i]會出錯
            {
                i--;
            }
            if(i < 0) //這裏須要break,由於可能一連串的空格,沒有任何字母,這時就應該及時退出
                break;
            lastend = i;
            while(i >= 0 && s[i] != ' ') //這裏也同樣,須要先保證i在合法範圍,再訪問s[i]
            {
                i--;
            }
            
            if(i <= lastend) // i may be -1
            {
                if(!result.empty())
					result.append(" "); // 至少有一個字符串時,須要添加空格
				result.append(s.substr(i+1, lastend - i));
            }
        }
        
		s.assign(result);
    }
};
相關文章
相關標籤/搜索