LeetCode 151. 反转字符串中的单词

题目描述

🔥 151. 反转字符串中的单词

image-20230305134732842

思路分析

双指针

参考代码

1
2
3
4
5
6
7
8
9
10
func reverseWords(s string) string {
	fields := strings.Fields(s)
	i, j := 0, len(fields)-1
	for i < j {
		fields[i], fields[j] = fields[j], fields[i]
		i++
		j--
	}
	return strings.Join(fields, " ")
}
1
2
3
4
5
6
7
8
9
10
11
func reverseWords(s string) string {
	fields := strings.Fields(s)
	reverse(fields)
	return strings.Join(fields, " ")
}

func reverse(slice []string) {
	for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
		slice[i], slice[j] = slice[j], slice[i]
	}
}
1
2
3
4
5
6
7
func reverseWords(s string) string {
	fields := strings.Fields(s)
	for i, j := 0, len(fields)-1; i < j; i, j = i+1, j+1 {
		fields[i], fields[j] = fields[j], fields[i]
	}
	return strings.Join(fields, " ")
}

🍏 点击查看 Java 题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
    public String reverseWords(String s) {
        String[] words = s.trim().split("\\s+");
        int left = 0;
        int right = words.length - 1;
        while (left < right) {
            String temp = words[left];
            words[left] = words[right];
            words[right] = temp;
            left++;
            right--;
        }
        return String.join(" ", words);
    }
}
本文作者:
本文链接: https://hgnulb.github.io/blog/2023/82558693
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!