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;
}
};

这道题还是不明白开头有空格怎么删除。

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