原题
给定一个字符串,逐个翻转字符串中的每个单词。
示例 1:
输入: “the sky is blue”
输出: “blue is sky the”
示例 2:
输入: “ hello world! ”
输出: “world! hello”
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: “a good example”
输出: “example good a”
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
说明:
- 无空格字符构成一个单词。
- 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
- 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
解法
一:直接使用jdk中String的trim()
和split()
方法得到单词的数组,或者遍历字符串字符,记录单词数组。再反向遍历输出。
class Solution {
public String reverseWords(String s) {
//"\\s+"代表正则表达式1个或多个空白字符
String[] words = s.trim().split("\\s+");
int size = words.length;
StringBuilder str = new StringBuilder();
for(int i = 0;i<size;i++){
str.append(words[size-1-i]);
if(i!=size-1) str.append(" ");
}
return str.toString();
}
}
二:递归
import "strings"
func reverseWords(s string) string {
return reverseWordsStart(s, 0)
}
func reverseWordsStart(s string, index int) string {
res := ""
started := false
for i := index; i < len(s); i ++ {
if s[i] == ' '{
if started{
after := reverseWordsStart(s, i+1)
if after != ""{
res = after + " " + res
}
return res
} else{
continue
}
}
started = true
res += string(s[i])
}
return res
}
三: 先反转整个字符串,再按单词反转,可以实现原地解法,此处省略代码
原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode151-%e7%bf%bb%e8%bd%ac%e5%ad%97%e7%ac%a6%e4%b8%b2%e9%87%8c%e7%9a%84%e5%8d%95%e8%af%8d/