转置字符串,其中单词内的字符需要正常
如题:转置一个字符串,需要其中的单词正常
例如:
Given s = "the sky is blue
",
return "blue is sky the
".
需要说明的是:
1、输入字符串可能会出现:前导空格,后置空格,要求输出的不能有前导空格和后置空格。
2、输入的语句中可能有两个单词之间出现多个空格,输出两个单词之间只能由一个空格。
#include <iostream> #include <string> using namespace std; void reverse(string &s,int start,int end) { while (start<end) { char tem = s[start]; s[start] = s[end]; s[end] = tem; start++; end--; } } void reverseString(string &s) { if (s.empty()||s.length()==0) { return; } //去除前置和后置空格 int num1 = s.find_first_not_of(" "); if (num1 == -1){ s = ""; return; } int num2 = s.find_last_not_of(" "); s = s.substr(num1,num2-num1+1); int start = 0,end = 0; int size = s.length(); end = size-1; //整个字符串倒置 reverse(s,start,end); //两个单词之间有多个空格的情况 int count = 0; for (int i = 0; i < size; i++) { if(s[i] == ' ' && s[i+1] == ' ')continue; s[count++]=s[i]; } if(count<size)s = s.substr(0,count); size = s.size(); start = 0; end = -2; //其中每个单词倒置 for (int i = 0; i < size; i++) { if(s[i] == ' ') { start = end+2; end = i-1; reverse(s,start,end); } if(i == size-1){ start = end+2; end = i; reverse(s,start,end); } } } int main(int argc, char **argv) { string s = " a b "; cout<<"before reverse: "<<s<<endl; reverseString(s); cout<<"after reverse: "<<s<<endl; return 0; }
posted on 2014-09-01 15:33 NewPanderKing 阅读(943) 评论(0) 编辑 收藏 举报