Reverse Words in a String

本文详细介绍了如何在不使用额外空间的情况下,实现字符串单词级别的反转。通过两段代码示例,展示了利用StringBuilder进行空间复杂度为O(n)的方法,以及仅使用O(1)额外空间的高效算法。

题目:

Given an input string s, reverse the string word by word.
For example, given s = "the sky is blue", return "blue is sky the"

 

Example Questions Candidate Might Ask:
Q: What constitutes a word?
A: A sequence of non-space characters constitutes a word.
Q: Does tab or newline character count as space characters?
A: Assume the input does not contain any tabs or newline characters.
Q: Could the input string contain leading or trailing spaces?
A: Yes. However, your reversed string should not contain leading or trailing spaces.
Q: How about multiple spaces between two words?
A: Reduce them to a single space in the reversed string.

 

解答:

 1 public String reverseWords(String s) {
 2 
 3     StringBuilder reversed = new StringBuilder();
 4     int j = s.length();
 5 
 6     for(int i = s.length()-1; i >= 0; i--) {
 7         if(s.charAt(i) == ' ') {
 8             j = i;
 9         } else if(i == 0 || s.charAt(i-1) == ' ') {
10             if(reversed.length() != 0) {
11                 reversed.append(' ');
12             }
13 
14             reversed.append(s.substring(i, j));
15         }
16     }
17 
18     return reversed.toString();
19 }

 

如果如何只允许使用O(1)的额外空间呢?

 1 public void reverseWords(char[] s) {
 2     reverse(s, 0, s.length);
 3     for(int i = 0, j = 0; j <= s.length; j++) {
 4         if(j == s.length() || s[j] == ' ') {
 5             reverse(s, i, j);
 6             i = j + 1;
 7         }
 8     }
 9 }
10 
11 public void reverse(char[] s, int begin, int end) {
12     for(int i = 0; i < (end - begin) >> 1; i++) {
13         char tmp = s[begin + i];
14         s[begin + i] = s[end -1 - i];
15         s[end -1 - i] = tmp;
16     }
17 }

 

转载于:https://www.cnblogs.com/wylwyl/p/10348414.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值