LeetCode 557. Reverse Words in a String III (反转字符串中的单词 III)
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.
题目标签:String
题目给了我们一串string,让我们把每一个word 给reverse一下。
设p1 和 p2,每一次让p2 找到 “ ” space,然后 reverse p1 和 p2 之间的 word,然后更新p1 和 p2 的值。
具体请看code。
Java Solution:
Runtime beats 96.43%
完成日期:05/31/2018
关键词:Two pointers
关键点:反转p1 和 p2 之间的 word
1 class Solution 2 { 3 public String reverseWords(String s) 4 { 5 char [] arr = s.toCharArray(); 6 int p1 = 0; 7 int p2 = 0; 8 9 while(p1 < arr.length) 10 { 11 // let p2 find the space 12 while(p2 < arr.length && arr[p2] != ' ') 13 p2++; 14 15 // once p2 find the space, do reverse between p1 and p2 16 int left = p1; 17 int right = p2 - 1; 18 19 while(left < right) 20 { 21 char temp = arr[left]; 22 arr[left] = arr[right]; 23 arr[right] = temp; 24 25 left++; 26 right--; 27 } 28 29 // reset p1 p2 30 p1 = p2 + 1; 31 p2++; 32 33 } 34 35 return new String(arr); 36 } 37 38 39 }
参考资料:n/a
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/