LeetCode 151. Reverse Words in a String && 186. Reverse Words in a String||&&557. Reverse

本文解析了LeetCode上三道关于翻转字符串中单词的题目,详细介绍了使用Java实现的不同方法,包括利用正则表达式进行字符串操作、原地翻转字符串中的单词以及按单词逆序字母等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

[LeetCode] 151 Reverse Words in a String 翻转字符串中的单词

 

Given an input string, reverse the string word by word.

For example,
     Given s = "the sky is blue",
     return "blue is sky the".

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

解题技巧预备知识

详解 "\\s+"

正则表达式中\s匹配任何空白字符,包括空格、制表符、换页符等等, 等价于[ \f\n\r\t\v]

  • \f -> 匹配一个换页
  • \n -> 匹配一个换行符
  • \r -> 匹配一个回车符
  • \t -> 匹配一个制表符
  • \v -> 匹配一个垂直制表符

而“\s+”则表示匹配任意多个上面的字符。另因为反斜杠在Java里是转义字符,所以在Java里,我们要这么用“\\s+”.

public String reverseWords(String s) {
    String[] tem = s.trim().split("\\s+");
    String res = "";
    for (int i = tem.length - 1; i > 0; i--) {
        res += tem[i] + " ";
    }
    res = res + tem[0];
    return res;

}


//原始方法 BY jeantimex 
//先逆转整个字符串,然后对逆转的字符串逆转每个词,最后去掉该去的空格
        public String reverseWords(String s) {
            if (s == null) return null;

            char[] a = s.toCharArray();
            int n = a.length;

            // step 1. reverse the whole string
            reverse(a, 0, n - 1);
            // step 2. reverse each word
            reverseWords(a, n);
            // step 3. clean up spaces
            return cleanSpaces(a, n);
        }

        void reverseWords(char[] a, int n) {
            int i = 0, j = 0;

            while (i < n) {
                while (i < j || i < n && a[i] == ' ') i++; // skip spaces
                while (j < i || j < n && a[j] != ' ') j++; // skip non spaces
                reverse(a, i, j - 1);                      // reverse the word
            }
        }

        // trim leading, trailing and multiple spaces
        String cleanSpaces(char[] a, int n) {
            int i = 0, j = 0;

            while (j < n) {
                while (j < n && a[j] == ' ') j++;             // skip spaces
                while (j < n && a[j] != ' ') a[i++] = a[j++]; // keep non spaces
                while (j < n && a[j] == ' ') j++;             // skip spaces
                if (j < n) a[i++] = ' ';                      // keep only one space
            }

            return new String(a).substring(0, i);
        }

        // reverse a[] from a[i] to a[j]
        private void reverse(char[] a, int i, int j) {
            while (i < j) {
                char t = a[i];
                a[i++] = a[j];
                a[j--] = t;
            }
        }


[LeetCode] 186. Reverse Words in a String II 翻转字符串中的单词之二


Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Could you do it in-place without allocating extra space?

/**
 * Created by happy on 17/4/25.
 */
public class ReverseWordsInaStringII {
    public static void reverseWords(char[] s) {
        String res="";
        //逆转整个字符串
        reverse(s,0,s.length-1);

        //逆转单个字符串
        for(int i=0,j=0;j<=s.length;j++){
            if(j==s.length||s[j]==' '){ //if(s[j]==' || j==s.length')如果这样写会数组下标越界
                reverse(s,i,j-1);
                i=j+1;}
        }
    }


    public static void reverse(char[] s, int start, int end){
        while(start<end){
            char tmp;
            tmp= s[end];
            s[end]=s[start];
            s[start]=tmp;
            start++;
            end--;
        }
    }
}

[LeetCode] 557. Reverse Words in a String III

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

Subscribe to see which companies asked this question.



 public static void reverse(char[] s, int start, int end){
        while(start<end){
            char tmp = s[end];
            s[end]=s[start];
            s[start]=tmp;
            start++;
            end--;
        }
    }

/*
557. Reverse Words in a String III
 */
    public static String reverseWords(String s) {
        char[] a = s.toCharArray();
        int start=0;
        for(int i=0;i<s.length();i++){
            if (a[i]==' '){
                int end=i-1;
                reverse(a,start,end);
                start=i+1;
            }
        }
        reverse(a, start,s.length() - 1);

        return new String(a);
    }
}



### 解决方案展示 #### 方法一:位操作 (Bit Manipulation) 对于给定的32位无符号整数,可以通过逐位反转来实现比特位的翻转。具体来说,在每次迭代中提取最低有效位并将其添加到结果中,随后将输入右移一位直到处理完所有的位[^1]。 ```python def reverseBits(n): res = 0 for i in range(32): res <<= 1 # 将当前的结果左移以为准备加入新的bit res |= n & 1 # 取得n最右边的一位加到结果上去 n >>= 1 # 把n往右移动以为方便下次循环取下一个bit return res ``` 这种方法的时间复杂度为O(logN),其中N是输入数值大小;空间复杂度则保持常量级别O(1)。 #### 方法二:分治策略 (Divide and Conquer with Cache) 另一种更高效的解决方案涉及使用预计算表来加速特定模式下的逆序过程。此方法利用预先构建好的字节级映射表快速完成部分转换工作,从而减少整体运算次数。通过这种方式可以在固定时间内完成整个32位数字的完全逆转[^2]。 ```python BYTE_MASKS = [0x55, 0x33, 0x0F] SWAPS = [ lambda b: ((b & BYTE_MASKS[0]) << 1) | ((b >> 1) & BYTE_MASKS[0]), lambda b: ((b & BYTE_MASKS[1]) << 2) | ((b >> 2) & BYTE_MASKS[1]), lambda b: ((b & BYTE_MASKS[2]) << 4) | ((b >> 4) & BYTE_MASKS[2]) ] def reverseByte(b): for swap in SWAPS: b = swap(b) return b def reverseBitsWithCache(x): result = 0 for _ in range(4): byte = x % 256 reversed_byte = reverseByte(byte) result = (result << 8) | reversed_byte x //= 256 return result ``` 这种优化后的版本能够显著提升性能表现特别是在面对大量重复调用场景下显得尤为突出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值