【LeetCode】151. 翻转字符串里的单词(Reverse Words in a String)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27124771/article/details/84584722

英文练习 | 中文练习

题目描述: 给定一个字符串,逐个翻转字符串中的每个单词。

示例:

输入: "the sky is blue"
输出: "blue is sky the"

说明:

  • 无空格字符构成一个单词。
  • 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
  • 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

解法一: 使用 Java API

public String reverseWords(String s) {
	// 正则式去掉空格
	String[] words = s.trim().split(" +");
	// 翻转
	Collections.reverse(Arrays.asList(words));
	// 单词间隔添加空格
	return String.join(" ", words);
}

解法二: 不使用 API ,纯裸写

    public String reverseWords(String s) {
        if (s == null) return null;
        
        char[] c = s.toCharArray();
        
        // 第一步:反转整个字符串
        reverse(c, 0, c.length - 1);
        // 第二步:反转每个单词
        reverseWords(c);
        // 第三步:清空空格
        return cleanSpaces(c);
        
    }
    
    // 反转所有单词
    public void reverseWords(char[] c){
        int i = 0, j = 0;
        
        while (i < c.length){
            while (i < j || i < c.length && c[i] == ' ') i++;      // 跳过空格
            while (j < i || j < c.length && c[j] != ' ') j++;      // 跳过非空格
            reverse(c, i, j - 1);
        }
    }
    
    // 去掉头部、尾部与中间的多余空格
    public String cleanSpaces(char[] c){
        int i = 0, j = 0;
        
        while (j < c.length){
            while (j < c.length && c[j] == ' ') j++;               // 跳过空格
            while (j < c.length && c[j] != ' ') c[i++] = c[j++];   // 去掉所有空格
            while (j < c.length && c[j] == ' ') j++;               // 跳过空格
            if (j < c.length) c[i++] = ' ';                        // 仅保留一个空格
        }
        
        return new String(c).substring(0, i);
    }
    
    // 从 i 到 j 反转数组 c
    public void reverse(char[] c, int i, int j){
        while(j > i){
            char t = c[i];
            c[i++] = c[j];
            c[j--] = t;
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_27124771/article/details/84584722