LeetCode第557題 反轉字符串中的單詞 III
阿新 • • 發佈:2019-02-18
() i++ take private arr iii rar oid 留空
給定一個字符串,你需要反轉字符串中每個單詞的字符順序,同時仍保留空格和單詞的初始順序。
示例 1:
輸入: "Let‘s take LeetCode contest"
輸出: "s‘teL ekat edoCteeL tsetnoc"
註意:在字符串中,每個單詞由單個空格分隔,並且字符串中不會有任何額外的空格。
思路:
簡單題
1.強行遍歷逆置
2.正則,分割字符串,逆置
1 class Solution557 {
2
3 public String reverseWords(String s) {
4 char[] arr = s.toCharArray();
5 int end = 0;
6 int start = 0;
7 for (end = 0; end < arr.length; end++) {
8 if (end == arr.length - 1 || arr[end + 1] == ‘ ‘) {
9 reserve(arr, start, end);
10 start = end + 2;
11 }
12 }
13 return new String(arr);
14 }
15
16 private void reserve(char [] arr, int start, int end) {
17 int len = end - start + 1;
18 for (int i = 0; i < (len >> 1); i++) {
19 char temp = arr[start + i];
20 arr[start + i] = arr[end - i];
21 arr[end - i] = temp;
22 }
23 }
24
25
26 public String reverseWords_2(String s) {
27 StringBuilder res = new StringBuilder();
28 String[] subs = s.split(" ");
29 for (String sub : subs) {
30 res.append(new StringBuilder(sub).reverse()).append(" ");
31 }
32 res.deleteCharAt(res.length() - 1);
33 return res.toString();
34
35 }
36 }
LeetCode第557題 反轉字符串中的單詞 III