【子串】151. 反转字符串中的单词【中等】

反转字符串中的单词

  • 给你一个字符串 s ,请你反转字符串中 单词 的顺序。

单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。

返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。

注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。

解题思路

  • 要反转字符串中的单词顺序,可以先将整个字符串进行反转,然后再逐个单词进行反转。
  • 这样就可以得到单词顺序颠倒的结果字符串。

java实现

java 复制代码
public class ReverseWords {
    public String reverseWords(String s) {
        // 去除字符串首尾空格,并将连续多个空格替换为一个空格
        //"\s" 表示空白字符,包括空格、制表符、换行符等
        //"\s+" 表示匹配一个或多个连续的空白字符
        s = s.trim().replaceAll("\\s+", " ");
        // 将字符串转换为字符数组
        char[] chars = s.toCharArray();
        // 反转整个字符串
        reverse(chars, 0, chars.length - 1);
        
        // 反转每个单词
        int start = 0;
        for (int end = 0; end < chars.length; end++) {
            if (chars[end] == ' ') {
                reverse(chars, start, end - 1);
                start = end + 1;
            }
        }
        // 反转最后一个单词
        reverse(chars, start, chars.length - 1);
        
        return new String(chars);
    }
    
    // 辅助函数:反转字符数组中指定范围的字符
    private void reverse(char[] chars, int left, int right) {
        while (left < right) {
            char temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;
            left++;
            right--;
        }
    }

    public static void main(String[] args) {
        ReverseWords reverseWords = new ReverseWords();
        String s1 = "the sky is blue";
        System.out.println("Test Case 1:");
        System.out.println("Input: \"the sky is blue\"");
        System.out.println("Reversed Words: \"" + reverseWords.reverseWords(s1) + "\""); // Expected: "blue is sky the"

        String s2 = "  hello world  ";
        System.out.println("\nTest Case 2:");
        System.out.println("Input: \"  hello world  \"");
        System.out.println("Reversed Words: \"" + reverseWords.reverseWords(s2) + "\""); // Expected: "world hello"
    }
}

时间空间复杂度

  • 时间复杂度: 遍历字符串的时间复杂度为 O(n),其中 n 是字符串的长度。
  • 空间复杂度: 使用了额外的字符数组,空间复杂度为 O(n),其中 n 是字符串的长度。
相关推荐
sg_knight2 分钟前
设计模式实战:策略模式(Strategy)
java·开发语言·python·设计模式·重构·架构·策略模式
麦麦鸡腿堡3 分钟前
JavaWeb_SpringBootWeb,HTTP协议,Tomcat快速入门
java·开发语言
qq_417695056 分钟前
内存对齐与缓存友好设计
开发语言·c++·算法
2301_816651227 分钟前
实时系统下的C++编程
开发语言·c++·算法
一然明月7 分钟前
Qt QML 锚定(Anchors)全解析
java·数据库·qt
晓纪同学7 分钟前
EffctiveC++_02第二章
java·jvm·c++
2401_831824967 分钟前
C++与Python混合编程实战
开发语言·c++·算法
2301_8166512215 分钟前
C++中的策略模式高级应用
开发语言·c++·算法