classSolution { public String reverseWords(String s) { StringBufferret=newStringBuffer(); intlength= s.length(); inti=0; while (i < length) { intstart= i; while (i < length && s.charAt(i) != ' ') { i++; } for (intp= start; p < i; p++) { ret.append(s.charAt(start + i - 1 - p)); } while (i < length && s.charAt(i) == ' ') { i++; ret.append(' '); } } return ret.toString(); } }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var reverseWords = function(s) { const ret = []; const length = s.length; let i = 0; while (i < length) { let start = i; while (i < length && s.charAt(i) != ' ') { i++; } for (let p = start; p < i; p++) { ret.push(s.charAt(start + i - 1 - p)); } while (i < length && s.charAt(i) == ' ') { i++; ret.push(' '); } } return ret.join(''); };
char* reverseWords(char* s) { int length = strlen(s); char* ret = (char*)malloc(sizeof(char) * (length + 1)); ret[length] = 0; int i = 0; while (i < length) { int start = i; while (i < length && s[i] != ' ') { i++; } for (int p = start; p < i; p++) { ret[p] = s[start + i - 1 - p]; } while (i < length && s[i] == ' ') { ret[i] = ' '; i++; } } return ret; }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funcreverseWords(s string)string { length := len(s) ret := []byte{} for i := 0; i < length; { start := i for i < length && s[i] != ' ' { i++ } for p := start; p < i; p++ { ret = append(ret, s[start + i - 1 - p]) } for i < length && s[i] == ' ' { i++ ret = append(ret, ' ') } } returnstring(ret) }
复杂度分析
时间复杂度:O(N),其中 N 为字符串的长度。原字符串中的每个字符都会在 O(1) 的时间内放入新字符串中。
classSolution { public: string reverseWords(string s){ int length = s.length(); int i = 0; while (i < length) { int start = i; while (i < length && s[i] != ' ') { i++; }
int left = start, right = i - 1; while (left < right) { swap(s[left], s[right]); left++; right--; } while (i < length && s[i] == ' ') { i++; } } return s; } };