6. Reverse Words in a String

Question:
Given an input string s, reverse the string word by word.
For example, given s = “the sky is blue”, return “blue is sky the”.

solution 1
用了一個輔助字符串,然後從後往前遍歷原字符串,遍歷到空格停止,將剛纔的單詞放入新字符串,需要兩個下標指針來定位,substr()是從主串中提取子字符串。
爲什麼我總是會發生自己看着挺對的但是就是編譯不過,希望有大神給我解答一下,快點教育明白我。

class Solution {
public:
    string reverseWords(string s) {
	int len = s.length();
	if (len == 0 || len == 1)
		return s;
	string news;
	int i = len - 1;
    while(s[i]==' ')
        i--;
	int j = i;
	int b = 0;//news的下標
	while (j>=0)
	{
		if (s[j] == ' '&& j!=0)
		{
			news += s.substr(j + 1, i - j);
			b += i - j - 1;
			news += ' ';
			i = j - 1; //從倒數第二個單詞開始進
			j = j - 1;
		}
		else if (j == 0&&s[j]!=' ')
		{
			news += s.substr(j, i - j + 1);
			j--;
		}	
		else
			j--;
	}
	return news;
}
};

這道題還是不明白開頭有空格怎麼刪除。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章