Reverse Words in a String 翻转一个字符串里的单词顺序 @LeetCode

LeetCode字符串翻转题解析
本文介绍了一道LeetCode上的简单题目:按单词翻转字符串。通过使用栈来实现字符串中每个单词的逆序输出,并保留单词间的单个空格。文章提供了完整的Java代码示例。

LeetCode新题,但是比较简单,直接用栈即可

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

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

click to show clarification.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

public class Solution {
    public String reverseWords(String s) {
        if(s.length() == 0) {
            return s;
        }
        Stack<String> stack = new Stack<String>();
        String[] ss = s.split("\\s+");
        for(String word : ss) {
            stack.push(word);
        }
        StringBuilder sb = new StringBuilder();
        while(!stack.isEmpty()) {
            sb.append(stack.pop()).append(" ");
        }
        return sb.toString().trim();
    }
}











### 实现方式:逐个反转每个单词 要实现翻转字符串中的每个单词并输出结果,可以通过以下步骤完成: - 首先去除字符串中的多余空格,确保单词之间只有一个空格。 - 遍历字符串,识别每个单词的起始和结束位置。 - 使用双指针技术反转每个单词。 #### Java 实现方式 以下是一个完整的 Java 实现,使用双指针反转每个单词: ```java public class ReverseWords { public String reverseWords(String s) { // 去除多余空格 s = s.trim(); // 将字符串转换为字符数组以便操作 char[] chars = s.toCharArray(); int start = 0; for (int i = 0; i <= chars.length; i++) { if (i == chars.length || chars[i] == ' ') { // 找到单词末尾,进行反转 reverse(chars, start, i - 1); start = i + 1; } } return new String(chars); } // 反转字符数组中的指定区间 private void reverse(char[] arr, int left, int right) { while (left < right) { char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right--; } } public static void main(String[] args) { ReverseWords rw = new ReverseWords(); String input = "hello world"; String output = rw.reverseWords(input); System.out.println("Input: " + input); System.out.println("Output: " + output); // 输出: "olleh dlrow" } } ``` #### Python 实现方式 Python 实现更加简洁,利用内置函数可以快速完成任务: ```python def reverse_words(s): # 分割字符串单词列表,并反转每个单词 return ' '.join(word[::-1] for word in s.split()) # 示例 input_str = "the sky is blue" output_str = reverse_words(input_str) print("Input:", input_str) print("Output:", output_str) # 输出: "eht yks si eulb" ``` #### C++ 实现方式 在 C++ 中,可以通过 `istringstream` 提取单词,并逐个反转: ```cpp #include <iostream> #include <sstream> #include <string> using namespace std; string reverseWords(string s) { istringstream iss(s); string word; string result; while (iss >> word) { reverse(word.begin(), word.end()); result += word + " "; } if (!result.empty()) { result.pop_back(); // 去除末尾多余的空格 } return result; } int main() { string input = "Let's take LeetCode contest"; string output = reverseWords(input); cout << "Input: " << input << endl; cout << "Output: " << output << endl; // 输出: "s'teL ekat edoCteel tsetnoc" return 0; } ``` 通过上述实现,可以有效地翻转字符串中的每个单词并输出结果。不同的编程语言提供了不同的实现方式,但核心思想是识别单词边界并逐个反转。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值