首页 > 其他 > 详细

LeetCode OJ - Reverse Words in a String

时间:2014-05-16 05:42:13      阅读:328      评论:0      收藏:0      [点我收藏+]

题目:

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

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

解题思路:

  1、先对字符串进行一次总的翻转

  2、以空格为单位,划分单词,然后对每个单词再进行一次翻转

代码:

  

bubuko.com,布布扣
class Solution {
public:
    void swap(char& a, char& b){
        int tmp = a;
        a = b;
        b = tmp;
    }
    void reverse(string &s, int begin, int end){
        if (s[begin] == \0 || s[end] == \0){
            return;
        }
        while (begin < end){
            swap(s[begin], s[end]);
            begin++;
            end--;
        }
    }
    void reverseWords(string &s) {
        if (s[0] == \0 || s.empty()){
            return;
        }
        reverse(s, 0, s.length() - 1);
        //*/
        int start = 0, end = 0, len = 0;
        while (start < s.length()){
            while (start != s.length() && s[start] ==  ) start++; //跳过对于的空格
            for (end = start; end != s.length() && s[end] !=  ; end++);
            if (len != 0 && end > start) s[len++] =  ;
            if (end > start){
                reverse(s, start, end - 1);
            }
            while (start < end) s[len++] = s[start++];
            
        }
        s.resize(len);
        //*/
    }
};
bubuko.com,布布扣

 

LeetCode OJ - Reverse Words in a String,布布扣,bubuko.com

LeetCode OJ - Reverse Words in a String

原文:http://www.cnblogs.com/dongguangqing/p/3726260.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!