string你不可能写inplace的。 要是非要上效率的。就是两个指针,从尾部读word,从头部读sperator. char[] char_arr = new char[len(s)]; int i = len(s) -1; int j = 0; // read word from end and save to char_arr while (i > -1 && j < len(s)){ // read word from end and save to char_arr reverse // read separtor from begin and save to char_arr } return new StringBuilder(char_arr).toString()
【在 d******e 的大作中提到】 : string你不可能写inplace的。 : 要是非要上效率的。就是两个指针,从尾部读word,从头部读sperator. : char[] char_arr = new char[len(s)]; : int i = len(s) -1; : int j = 0; : // read word from end and save to char_arr : while (i > -1 && j < len(s)){ : // read word from end and save to char_arr reverse : // read separtor from begin and save to char_arr : }
l*s
27 楼
C# Solution. Tested. 2-Pointer in space O(n) time private string reverse(string s){ StringBuilder result = new StringBuilder(); for (int left = 0, right = s.Length - 1; left < s.Length || right >= 0;){ while (left < s.Length && !char.IsLetter(s[left])) result.Append(s[left++]); while (right >= 0 && !char.IsLetter(s[right])) right--; int newRight = right; while (newRight > 0 && char.IsLetter(s[newRight - 1])) newRight--; if (newRight >= 0){ result.Append(s.Substring(newRight, right - newRight + 1)); right = newRight - 1; } while (left < s.Length && char.IsLetter(s[left])) left++; } return result.ToString(); }