码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Words in a String--LeetCode

时间:2015-04-13 11:01:46      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   算法   

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

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

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

思路:做两次旋转 和Rotate Array相似

void reverseChar(string& s,int begin,int end)
{
     if(end < begin)
      return ;
     while(begin <= end)
     {
         swap(s[begin],s[end]);
         begin++;
         end--;        
     }
}
void reverseWords(string &s) 
{
     int len = s.length();
     int i,j;
     reverseChar(s,0,len-1);
     for(i=0;i<len;)
     {
        for(j=i;j<len;j++)
          if(s[j] == ' ')
            break;
        reverseChar(s,i,j-1);
        i = j+1;
     }       
}


Reverse Words in a String--LeetCode

标签:c++   leetcode   算法   

原文地址:http://blog.csdn.net/yusiguyuan/article/details/45021687

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!