首页 > 代码库 > 151. Reverse Words in a String (String)
151. Reverse Words in a String (String)
思路: 本题考查的目的并不是使用字符串的函数。方法是两次reverse,先对每个单词先做一次翻转,然后对整个字符串做一次翻转。
需要注意的是去除extra space,并且对全space字符串、以及最后一个单词要做特殊处理。
class Solution { public: void reverseWords(string &s) { int start = 0; int end=-1; int i = 0; int cur = 0; // point to the string with extra space deleted //ignore space at the beginning while(i < s.length() && s[i]==‘ ‘){ i++; } for(;i<s.length();i++){ if(s[i]==‘ ‘ && i+1 < s.length() && s[i+1] ==‘ ‘) continue; //ignore extra space between words if(s[i]==‘ ‘ && i+1 == s.length()) break; //ignore final space s[cur++] = s[i]; if(s[i]==‘ ‘){ end = cur-2; //end case1: the letter before space reverse(s, start, end); start = cur; } } end = cur-1; //end case2: the last not space letter!!! if(end == -1) s = ""; //special case: null string!!! if(s[i-1] != ‘ ‘){ //reverse the last word!!! reverse(s,start,end); } cout << "end=" << end << endl; s = s.substr(0, end+1); reverse(s,0,end); } void reverse(string &s, int start, int end){ int l = start; int r = end; char tmp; while(l<r){ tmp = s[l]; s[l]=s[r]; s[r]=tmp; l++; r--; } } };
151. Reverse Words in a String (String)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。