Loading

[LeetCode]翻转字符串里的单词

题目

 

代码 

class Solution {
public:
	void reverseWords(string &s) {
		if (s.empty()) return;
        
        //-----判断是否不包含单词,全是空格
		bool isSpace = true;
		for (auto i : s)
		{
			if (i != ' ')
				isSpace = false;
		}
		if (isSpace)
		{
			s = "";
			return;
		}

        
        //-----移除字符串头和尾的空格
		int startPos = s.find_first_not_of(' ');
		int endPos = s.find_last_not_of(' ');
		if (startPos == string::npos || endPos == string::npos)
			return;
		s = s.substr(startPos, endPos - startPos+1);
   
        
        //-----去除字符串中多余的空格
		int restSpace = 0;
		int pre = 1, end = 1;
		while (end < s.size())
		{
			if (s[end] == ' '&&s[end - 1] == ' ')
			{
				end++;
				restSpace++;
			}
			else
			{
				s[pre] = s[end];
				pre++;
				end++;
			}
		}
		s.resize(s.size() - restSpace);
        
        
        //-----将字符串进行反转
		reverse(s.begin(), s.end());
		for (int i = 0, j = 0; j <= s.size(); j++)
		{
			if (j == s.size() || s[j] == ' ')
			{
				reverse(s.begin() + i, s.begin() + j);
				i = j + 1;
			}

		}

	}
};

 

posted @ 2019-02-23 12:07  李正浩  阅读(113)  评论(0编辑  收藏  举报