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.

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.

讲一个字符串中的单词逆序输出,单词中字母顺序不发生改变。其中,字符串首位的空格应删去,字符串中如果存在多余的空格,只需输出一个空格。

思路一:正则表达式

关于正则表达式的详细信息,请参考我的这篇博客
在这里,我们只需要将句子中的单词通过split的正则表达式读取出来即可。这里用到的正则表达式为\s+,也就是遇到一个或多个空白时断句。

    public String reverseWords(String s) {
        String[] array = s.trim().split("\\s+");
        String result = "";
        for(int i = array.length-1 ; i>0 ; i--){
            result += array[i] + " ";
        }
        return result + array[0];
    }

思路二:双指针

其实双指针这里也用了String的API,不过核心的思路还是在于通过双指针找到一个单词的位置,然后通过获得子字符串的方法将其提取出来加入到结果集中。

    public String reverseWords(String s){
        String trimmed = s.trim();
        int prev = trimmed.length();
        int index = prev;
        StringBuilder result = new StringBuilder();
        while ((index = trimmed.lastIndexOf(' ', index-1)) > 0) {
            if (index < prev-1) {
                result.append(trimmed.substring(index+1, prev));
                result.append(" ");
            }
            prev = index;
        }
        result.append(trimmed.substring(index+1, prev));
        return result.toString();
    }

clipboard.png
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注我的微信公众号!将会不定期的发放福利哦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值