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 public String reverseWords(String s) { 2 String[] words = s.split(" "); 3 StringBuilder result = new StringBuilder(); 4 for (String word:words) 5 { 6 String newWord = new StringBuilder(word).reverse().toString(); 7 result.append(newWord).append(" "); 8 } 9 return result.toString().trim(); 10 }
方法二:
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 }