[Leetcode] Reverse Words in a String

本文详细介绍了如何实现字符串中单词的翻转,并通过两种不同的解决方案解释了算法原理及其实现过程。其中包括一次扫描翻转和整体翻转后再翻转每个单词的方法,确保输出的字符串格式符合指定规范。

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

Reverse Words in a String

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

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


Clarification:

  • 1 What constitutes a word? 
  • A sequence of non-space characters constitutes a word.
  • 2 Could the input string contain leading or trailing spaces? 
  • Yes. However, your reversed string should not contain leading or trailing spaces.
  • 3  How about multiple spaces between two words?   
  • Reduce them to a single space in the reversed string.
Solution1:一次扫描翻转。 设置两个动态游标,last表示 未被扫描的结尾处, i表示word之前空格处
public class Solution {
	public String reverseWords(String s) {
		if (s == null)
			return "";
		s = s.trim();
		if (s == "")
			return "";
		StringBuffer sb = new StringBuffer();
		int i = s.length() - 1;
		int last = i;
		while (i >= 0) {
			while (i >= 0 && s.charAt(i) != ' ') {
				i--;
			}
			String temp = s.substring(i + 1, last + 1);
			sb.append(temp);
			sb.append(" ");
			while (i >= 0 && s.charAt(i) == ' ') {
				i--;
			}
			last = i;
		}
		while (sb.length() > 1 && sb.charAt(sb.length() - 1) == ' ')
			sb.deleteCharAt(sb.length() - 1);
		return sb.toString();
	}
}

Solution2:先整体翻转,然后再每个word翻转。 利用一个Stack,注意最后的结尾处

static String reverseWords(String str) {
		System.out.println(str);
		char[] strCh = str.toCharArray();
		int len = strCh.length;
		char[] tmp = new char[len];

		for (int i = 0; i < len; i++) {
			tmp[len - i - 1] = strCh[i];
		}

		Stack stack = new Stack();
		int wordLen = 0;

		for (int i = 0; i < len; i++) {
			if (tmp[i] == ' ' || tmp[i] == ',' || tmp[i] == '?') {
				for (int j = 0; j < wordLen; j++) {
					tmp[i - wordLen + j] = (char) stack.pop();
				}
				wordLen = 0;
				stack.clear();
			} else if (i == len - 1) {
				stack.push(tmp[i]);
				wordLen++;
				for (int j = 0; j < wordLen; j++) {
					tmp[i - wordLen + j + 1] = (char) stack.pop();
				}
			} else {
				stack.push(tmp[i]);
				wordLen++;
			}
		}

		return new String(tmp);
	}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值