-
SLPHPython解法一:
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ return ' '.join(w[::-1] for w in s.split())
-
SLPHPython解法二:
class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ clist, size = list(s), len(s) p = q = 0 while p < size: while q < size and s[q] != ' ': q += 1 for x in range((q - p) / 2): clist[p + x], clist[q - x - 1] = clist[q - x - 1], clist[p + x] p = q = q + 1 return ''.join(clist)
-
SLPHC++解法一:
class Solution { public: string reverseWords(string s) { string res = "", t = ""; istringstream is(s); while (is >> t) { reverse(t.begin(), t.end()); res += t + " "; } res.pop_back(); return res; } };
-
SLPHC++解法二:
class Solution { public: string reverseWords(string s) { int start = 0, end = 0, n = s.size(); while (start < n && end < n) { while (end < n && s[end] != ' ') ++end; for (int i = start, j = end - 1; i < j; ++i, --j) { swap(s[i], s[j]); } start = ++end; } return s; } };
-