算法笔记|Day8字符串II
☆☆☆☆☆leetcode 151.翻转字符串里的单词
题目分析
1.此题需要完成三个步骤:移除多余空格,将整个字符串反转,将每个单词反转;
2.移除空格需要注意:首尾的空格应删掉,每两个单词之间要保留一个空格,同时为了保证删去多余的元素,应该对数组重新resize;
3.时间复杂度为O(n),空间复杂度为O(1)。
代码
class Solution {
public String reverseWords(String s) {
char ch[]=s.toCharArray();
ch=removeSpaces(ch);
reverse(ch,0,ch.length-1);
reverseEachWord(ch);
return new String(ch);
}
public char[] removeSpaces(char[] ch){
int slow=0,fast=0;
for(;fast<ch.length;fast++){
if(ch[fast]!=' '){
if(slow!=0){
ch[slow]=' ';
slow++;
}
while(fast<ch.length&&ch[fast]!=' '){
ch[slow]=ch[fast];
slow++;
fast++;
}
}