1. 程式人生 > >LeetCode 557. Reverse Words in a String III (反轉字符串中的單詞 III)

LeetCode 557. Reverse Words in a String III (反轉字符串中的單詞 III)

logs clas code 資料 tno beats target eat 6.4

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/

LeetCode 557. Reverse Words in a String III (反轉字符串中的單詞 III)