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

leetcode——Reverse Words in a String 旋转字符串中单词顺序(AC)

时间:2015-02-11 14:16:19      阅读:128      评论: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".

click to show clarification.

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.
题目要求不仅须要把字符串中的单词进行旋转,并且測试用例中还包括头尾含有空格、单词间空格数大于1个之类的字符串。所以要处理好空格,处理完空格的字符串肯定是小于或等于原字符串长度的,考虑到通过移动字符的方式来减小空格耗时长,我的思路是首先计算出去多余的空格后字符串应有的长度,然后又一次定义一个暂时字符串,开辟终于应有长度的空间。然后将原字符串逆序copy到新定义的字符串变量中,保证头尾多余空格已去除,保证单词间仅保留一个空格。然后将每一个单词再进行一次反转,便实现了题目所要求的功能。AC代码例如以下:
class Solution {
public:
    void reverseWords(string &s) 
	{
		if(s.empty())
			return;
		int count = 0;
		int index = 0, indexTemp = 0, begin = 0, end = s.length()-1;
		while(s[begin] == ' ' && begin<s.length()-1)
			begin++;
		while(s[end] == ' ' && end>0)
			end--;
		if(end == 0 && s[end] == ' ')
		{
			s = "";
			return;
		}
		else if(end == 0)
		{
			s = s.substr(0,1);
			return;
		}
		index = begin;
		while(index <= end)
		{
			if(s[index] == ' ')
			{
				count++;
				while(s[index] == ' ')
					index++;
			}
			count++;
			index++;
		}
		string temp(count,'\0');
		index = end;
		indexTemp = 0;
		while(index >= begin)
		{
			if(s[index] == ' ')
			{
				temp[indexTemp] = s[index];
				while(s[index] == ' ')
					index--;
				indexTemp++;
			}
			temp[indexTemp] = s[index];
			indexTemp++;
			index--;
		}
		indexTemp = 0;
		begin = -1;
		end = -1;
		while(indexTemp < count)
		{
			if(temp[indexTemp] != ' ' && begin == -1)
			{
				begin = 0;
			}
			else if(indexTemp-1 >= 0 && temp[indexTemp-1] == ' '&&temp[indexTemp] != ' ')
			{
				begin = indexTemp;
			}
			else if((indexTemp+1 < count && temp[indexTemp+1] == ' ' && temp[indexTemp] != ' ') || ((indexTemp == count-1)&&temp[indexTemp] != ' '))
			{
				end = indexTemp;
				reverse(temp, begin, end);

			}
			indexTemp++;
		}
		s = temp;
    }
	
	void reverse(string &s, int begin, int end)
	{
		while(begin < end)
		{
			char temp = s[begin];
			s[begin] = s[end];
			s[end] = temp;
			begin++;
			end--;
		}
	}
};



leetcode——Reverse Words in a String 旋转字符串中单词顺序(AC)

标签:

原文地址:http://www.cnblogs.com/gcczhongduan/p/4285803.html

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