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

LeetCode OJ - Reverse Words in a String

时间:2014-05-16 05:44:30      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   java   

题目:

  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

标签:style   blog   class   code   c   java   

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

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