关闭

leetcode - Reverse Words in a String

224人阅读 评论(0) 收藏 举报
分类:

题意:

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.

click to show clarification.

思路:先将字符串中连续空格删除,不同单词之间仅保留一个空格。同时将开始的空格删除,结尾的空格删除。

         然后将字符串进行就地逆置,将字符串的各个单词进行就地逆置。

       

class Solution {
public:
    void delete_kong(string &s)
    {
        int i = 0;
        int len = s.length();
        int index = 0;
        for(i = 0;i<len;i++)
        {
            if(s[i] == ' ')
            continue;
            else
            break;
        }
        int j = i;
        for(j = i;j<len;j++)
        {
            if(s[j] == ' ' && j+1<len && s[j+1] == ' ')
             {
                 continue;
             }
             else
            {
                s[index] = s[j];
                index++;
            }
        }
        if(s[index-1] == ' ')
            index--;
        s = s.substr(0,index);

    }
    void reverse(string &s,int start,int end)
    {
        int i = 0;
        int mid = (end-start)/2;
        for(i = 0;i<=mid;i++)
        {
            char temp = s[start+i];
            s[start+i]= s[end-i];
            s[end-i] = temp;
        }
    }
    void reverseWords(string &s) {

        int i = 0;
        if(s == " " || s== "")
          s = "";
        delete_kong(s);

        int len = s.length();
        int start = 0;
        int end = len-1;
        reverse(s,start,end);
        //cout<<s<<endl;

        for(i = 0;i<len;i++)
        {
            if(s[i] == ' ')
            {

                if((i-1)>=0)
                {
                    end = i-1;
                    reverse(s,start,end);
                    start = i+1;
                    end = i+1;
                }
            }
        }
        end = len-1;
        reverse(s,start,end);
        }

};

        

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7853次
    • 积分:327
    • 等级:
    • 排名:千里之外
    • 原创:25篇
    • 转载:9篇
    • 译文:0篇
    • 评论:0条
    文章分类