Posts Tagged 【String】 Reverse Words in a String

Reverse Words in a String

  Total Accepted: 60944  Total Submissions: 406484 My Submissions

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.

//java好像没啥好讲的,用个正则表达式很好split
/*
input="   a      b "
output="b a"
貌似是这个要求就ac了
*/
public class Solution {
    public String reverseWords(String s) {
        String[] str = s.trim().split("[ ]+");
        StringBuilder sb = new StringBuilder();
        for(int i = str.length-1;i>0;i--) {
        	sb.append(str[i]+" ");
        }
        if(str.length > 0)
        	sb.append(str[0]);
        return sb.toString();
    }
}
//Integer--int--char转化
/*
没觉得这个有啥好
写上去的感觉,提供另一个很好地想法:词和句子。
并且用的是栈
如果题目要求多点,比如符号啥点,可以这么来考虑
当然,如果像前面的正表来split,啥都不说了
*/
public class Solution {
    public String reverseWords(String s) {
        String ss = s.trim();
        Stack<Character> word = new Stack<Character>();
        Stack<Character> sentence = new Stack<Character>();
        StringBuilder sb = new StringBuilder();
        for(int i = 0;i<ss.length();i++) {
            char a = ss.charAt(i);
            if(a != ' ') word.push(a);
            else {
                //两个while去掉多个空格
            	while(!word.isEmpty()) {
                    while(!word.isEmpty()) {
                        sentence.push(word.pop());
                    }
                    sentence.push(' ');
            	}
            }
        }
        //"hil"没有遇到空格,第一次
        while(!word.isEmpty()) {
            sentence.push(word.pop());
        }
        while(!sentence.isEmpty()) {
            sb.append(sentence.pop());
        }
        return sb.toString();
    }
}





Have you met this question in a real interview?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值