您的位置:首页 > 其它

LeetCode:Reverse Words in a String

2014-04-29 20:22 267 查看
Reverse Words in a String

题目链接:http://oj.leetcode.com/problems/reverse-words-in-a-string/

  

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

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

  Clarification:

What constitutes a word?
A sequence of non-space characters constitutes a word.

Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.

How about multiple spaces between two words?
Reduce them to a single space in the reversed string.

题目大意:给定一个字符串,对字符串进行逆转。

解题思路:看到这道题目有两种思路:

    1)用两个指针从前到后扫描,分开单词,先对每个单词进行逆转,最后再对整个字符串逆转;

    比如题目中给的例子:先对每个单词进行逆转得到的结果:"eht yks si eulb",然后再整体逆转即可得到"blue is sky the"。

    2)根据空格切分字符串,将切分得到的单词存到vector中,然后将vector中的单词从末尾开始输出即可。

    在衡量了两种方法之后,觉得第二种方法代码更加简洁方便,便选择了第二种思路。   

实现:

void reverseWords(string &s) {
int i=0,j=0;
int len = s.length();
vector<string> splitResult;

while(i<len)
{
if(s[i]==' ')
i++;
else
{
j=i+1;
while(j<=len)
{
if(s[j]==' '||j==len)
{
string tempStr = s.substr(i,j-i);
splitResult.push_back(tempStr);
i=j+1;
break;
}
else
j++;
}

}
}
int size = splitResult.size();
if(size>0)
{
s="";
for(i=size-1;i>0;i--)
s+=splitResult[i]+" ";
s+=splitResult[i];
}
else
{
s="";
}

}


  注意的地方:我一开始提交就提示错误,要考虑到空字符串以及只有空格组成的字符串,因此要在最后作一个判断,如果splitResult为空,则直接把s赋值为""即可。  

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: