LeetCode 151 - Reverse Words in a String

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

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

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

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.

Solution 1: two-pass.

public String reverseWords(String s) {
    String[] words = s.trim().split("\\s+");
	if(words.length == 0) {
        return "";
    }
	StringBuilder sb = new StringBuilder(words[words.length-1]);
	for(int i=words.length-2; i >=0; i--) {
		sb.append(" "+words[i]);
	}
	return sb.toString();
}

 

Solution 2: one-pass.

We can do better in one-pass. While iterating the string in reverse order, we keep track of a word’s begin and end position. When we are at the beginning of a word, we append it.

public String reverseWords(String s) {
    StringBuilder sb = new StringBuilder();
    int end = s.length();
    int i = end-1;
    while(i>=0) {
        if(s.charAt(i) == ' ') {
            if(i < end-1) {
                sb.append(s.substring(i+1, end)).append(" ");
            }
            end = i;
        }
        i--;
    }
    sb.append(s.substring(i+1, end));
    return sb.toString().trim();
}

 

重构了以下以上代码:

public String reverseWords(String s) {
    StringBuilder sb = new StringBuilder();
    int last = s.length();
    for(int i=s.length()-1; i>=-1; i--) {
        if(i==-1 || s.charAt(i)==' ') {
            String word = s.substring(i+1, last);
            if(!word.isEmpty()) {
                if(sb.length() != 0) sb.append(' ');
                sb.append(word);
            }
            last = i;
        }
    }
    return sb.toString();
}

 

Solution 3:

public String reverseWords(String s) {
    if(s == null || s.isEmpty()) return s;
    char[] data = s.toChartArray();
    int n = data.length;
    reverse(data, 0, n-1);
    
    int last = -1;
    for(int i=0; i<=n; i++) {
        if(i == n || data[i] == ' ') {
            if(i-last>1) reverse(data, last+1, i-1);
            last = i;
        }
    }
    
    return new String(data);
}

private void reverse(char[] data, int start, int end) {
    while(start < end) {
        char tmp = data[start];
        data[start++] = data[end];
        data[end--] = tmp;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值