标签:style blog io color sp on div log bs
将句子的词反转,例如:
Given s = "the sky is blue
",
return "blue is sky the
".
思路:就是从后面往前,找到非空格的长度,然后取到另一个串中。遍历一次就可以了。如下:
class Solution { public: void reverseWords(string &s) { if (s.size() < 1) return ; int ind = s.size() - 1, wordLen = 0, tmpind; string ans = ""; while(ind >=0) { wordLen = 0; while(ind >= 0 && s[ind] == ‘ ‘) ind--; tmpind = ind; while(ind >= 0 && s[ind] != ‘ ‘) ind--; wordLen = tmpind - ind; if (wordLen > 0) { if (ans.size() == 0) ans = s.substr(ind + 1, wordLen); else ans = ans + ‘ ‘ + s.substr(ind + 1, wordLen); } ind--; } s = ans; } };
这次又出现 unlock the question,然后评分
leetcode Reverse Words in a String
标签:style blog io color sp on div log bs
原文地址:http://www.cnblogs.com/higerzhang/p/4171010.html