Re: [閒聊] 每日LeetCode已回收
151. Reverse Words in a String
給與一個字串s,將句子裡的所有單字(word)順序顛倒,並去除大於一個和在頭尾的空格。
Example:
Input: s = "the sky is blue"
Output: "blue is sky the"
Input: s = " hello world "
Output: "world hello"
Input: s = "a good example"
Output: "example good a"
思路:
1.把字串s用正則表達式依據空白切開成多個部分
2.從尾放到頭,如果被切開的字串不是空白就appende該字串並加上空白分隔符。
3.最後把多出的空白分隔符刪除即可。
Java Code:
--------------------------------
class Solution {
public String reverseWords(String s) {
String[] strs = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = strs.length - 1; i >= 0; i--) {
if (strs[i].length() > 0) {
sb.append(strs[i]).append(" ");
}
}
return sb.substring(0, sb.length() - 1);
}
}
--------------------------------
https://i.imgur.com/y5dG1YA.png


--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 49.159.111.108 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1668325779.A.F5F.html
→
11/13 15:51,
3年前
, 1F
11/13 15:51, 1F
推
11/13 15:53,
3年前
, 2F
11/13 15:53, 2F
→
11/13 16:03,
3年前
, 3F
11/13 16:03, 3F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 99 之 719 篇):