目录

258.反转字符串中的单词

目录

258.反转字符串中的单词

https://i-blog.csdnimg.cn/direct/66c87e100e0343fc81eb736a485f5689.png

方法一:

public class Solution {
    public String reverseWords(String s) {
        if(s.length()==1&&!s.equals(" ")){
            return s;
        }
        List<String> res=new ArrayList<>();
        int start=0;
        for(int i=1;i<s.length();i++){
            if(s.charAt(i)!=' '&& s.charAt(i - 1)==' '){
                start=i;
            }
            if(s.charAt(i-1)!=' '&&s.charAt(i)==' '){
                res.add(s.substring(start,i));
            }
            if(i==s.length()-1&&s.charAt(i)!=' '){
                res.add(s.substring(start,i+1));
            }
        }
        Collections.reverse(res);
        return String.join(" ", res);
    }
}
class Solution(object):
    def reverseWords(self, s):
        if len(s)==1 and s!=" ":
            return s
        res=list()
        start=0
        for i in range(1,len(s)):
            if s[i]!=" " and s[i-1]==" ":
                start=i
            if s[i-1]!=" " and s[i]==" ":
                res.append(s[start:i])
            if i==len(s)-1 and s[i]!=" ":
                res.append(s[start:i+1])
        res.reverse()
        return " ".join(res)

方法二:

public class Solution {
    public String reverseWords(String s) {
        // 使用 split 方法将字符串按空格分割成单词数组
        // 注意:split 方法会处理多余的空格
        String[] words = s.trim().split("\\s+");
        // 使用双指针反转单词数组
        int left = 0, right = words.length - 1;
        while (left < right) {
            String temp = words[left];
            words[left] = words[right];
            words[right] = temp;
            left++;
            right--;
        }
        // 使用 String.join 将单词数组拼接成字符串
        return String.join(" ", words);
    }
}
class Solution(object):
    def reverseWords(self, s):
        # 先反转整个句子,然后反转其中的每个单词
        # 空间复杂度为O(1)的解法
        words = s.split()
        left, right = 0, len(words) - 1
        while left < right:
            words[left], words[right] = words[right], words[left]
            left += 1
            right -= 1
        return " ".join(words)