[LeetCode] Reverse Words in a String

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.

思路:用s.substr(pos,num)把s中的子字符串取出来,存放在栈strStack中

         然后把每个子字符串从strStack中取出来组合成s;

注意事项:

1.s.subStr(0,0)的结果是“”,即空字符串;

2.测试用例:

   (1)字符串首有空格、字符串末尾有空格、字符串中间有连续多个空格

   (2)空字符串

   (3)只有空格的字符串

 

class Solution
{
public:
    void reverseWords(string &s)
    {
        if(s.size() == 0)
            return;
        string::size_type pos=0,num=0,n=0;
        stack<string> strStack;

        while(n < s.size())
        {
            while( n < s.size() && s[n] == ' ')
            {
                ++n;
            }
            string::size_type num=0;
            if( n < s.size() && s[n] != ' ')     //找子字符串的初始位置pos,有可能找不到,pos=0
            {
               pos = n;
               ++num;
               ++n;
            }
            while( n < s.size() && s[n] != ' ')  //计算子字符串的长度num,有可能num=0
            {
               ++n;
               ++num;
            }
           string subS = s.substr(pos,num); // s.substr(0,0)=""
           if(subS != "")
               strStack.push(subS);
        }

    
        if(strStack.empty()) //有可能原s=“   ”(几个空格),栈中什么都没有,则s就不会从栈中得到但期望的结果是""(空字符串)。
        {
           s = "";
        }
        else
        {
          s = strStack.top();
          strStack.pop();
        }

        while(!strStack.empty())
        {
           s += ' ';
           s += strStack.top();
           strStack.pop();
        }
        
    }
};

 

 

 

posted @ 2014-06-05 18:59  Xylophone  Views(172)  Comments(0Edit  收藏  举报