557. Reverse Words in a String III【easy】
557. Reverse Words in a String III【easy】
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let‘s take LeetCode contest" Output: "s‘teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
解法一:
1 class Solution { 2 public: 3 void reverseSelf(string & s, int start, int end) 4 { 5 while (start <= end) { 6 char c = s[start]; 7 s[start] = s[end]; 8 s[end] = c; 9 ++start; 10 --end;11 } 12 } 13 14 string reverseWords(string s) { 15 int i = 0; 16 17 while (i < s.length()) { 18 int j = i; 19 while (j < s.length() && s[j] != ‘ ‘) { 20 ++j; 21 } 22 23reverseSelf(s, i, j - 1); 24 25 i = j + 1; 26 } 27 28 return s; 29 } 30 };
無他,註意下標邊界爾。
解法二:
1 public String reverseWords(String s) 2 { 3 char[] s1 = s.toCharArray(); 4 int i = 0; 5 for(int j = 0; j < s1.length; j++) 6 { 7 if(s1[j] == ‘ ‘) 8 { 9 reverse(s1, i, j - 1); 10 i = j + 1; 11 } 12 } 13 reverse(s1, i, s1.length - 1); 14 return new String(s1); 15 } 16 17 public void reverse(char[] s, int l, int r) 18 { 19 while(l < r) 20 { 21 char temp = s[l]; 22 s[l] = s[r]; 23 s[r] = temp; 24 l++; r--; 25 } 26 }
參考@sooryaprasanna 的代碼
Step 1. Convert the string to char[] array
Step 2. Whenever I encounter a space ‘ ‘ , I call the reverse function ( just to keep the code clean )
Step 3. Repeat till the end!
解法三:
1 class Solution { 2 public: 3 string reverseWords(string s) { 4 for (int i = 0; i < s.length(); i++) { 5 if (s[i] != ‘ ‘) { // when i is a non-space 6 int j = i; 7 for (; j < s.length() && s[j] != ‘ ‘; j++) { } // move j to the next space 8 reverse(s.begin() + i, s.begin() + j); 9 i = j - 1; 10 } 11 } 12 13 return s; 14 } 15 };
參考@alexander 的代碼。
補充一下reverse函數:
reverse函數可以反轉一個容器中的內容,包含在<algorithm>庫中。
1、函數原型
reverse函數等同於下面的代碼:
1 template <class BidirectionalIterator> void reverse (BidirectionalIterator first, BidirectionalIterator last) 2 { 3 while ((first!=last)&&(first!=--last)) 4 { 5 std::iter_swap (first,last); 6 ++first; 7 } 8 }
reverse函數使用iter_swap來交換兩個元素。
2、參數:first、last
first和last是雙向叠代器類型,reverse函數反轉的範圍是[first,last),所以包括first指向的元素,不包括last指向的元素。
3、返回值
reverse函數沒有返回值。
參考自:http://blog.csdn.net/u012877472/article/details/49557077
557. Reverse Words in a String III【easy】