问题描述:
Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
把单词(单词内部)逆序,整个字符串的词序不变,空格位置不变。
举例:
Input: s = “Let’s take LeetCode contest”
Output: “s’teL ekat edoCteeL tsetnoc”
限定条件:
1 <= s.length <= 5 * 10000
s contains printable ASCII characters.
s does not contain any leading or trailing spaces.
There is at least one word in s.
All the words in s are separated by a single space.
思路:
遍历字符串,如果某一位是空格,则在目标字符串中加入该元素;若某一位不是空格,则在一个临时的list中加入该元素,且这时如果下一位是空格,说明这段时间内在list上已经储存了一个完整单词,是时候把它倒序输出了,而且倒序输出后清空list
代码如下:
class Solution {
public String reverseWords(String s) {
s=s+" ";
StringBuilder sb = new StringBuilder();
List<Character> list = new ArrayList<>();
for(int i=0; i<s.length()-1;i++){
if(s.charAt(i)==' '){
sb.append(s.charAt(i));
}
else{
list.add(s.charAt(i));
if(s.charAt(i+1)==' '){
for(int j=list.size()-1; j>=0; j--){
sb.append(list.get(j));
}
list.clear();
}
}
}
return sb.toString();
}
}
时间复杂度:O(n)