【LintCode】Reverse Words in a String 翻转字符串

98 篇文章 0 订阅
6 篇文章 0 订阅

中文描述:
给定一个字符串,逐个翻转字符串中的每个单词。
我曾在百度的实习面试中遇到过这道题。

样例
给出s = “the sky is blue”,返回”blue is sky the”

说明
单词的构成:无空格字母构成一个单词。
输入字符串是否包括前导或者尾随空格?可以包括,但是反转后的字符不能包括。
如何处理两个单词间的多个空格?在反转字符串中间空格减少到只含一个。

English Version:

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

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

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.

基本思路:
1)第一趟遍历
将每个单词翻转,且去掉连续空格中多余的空格(两端空格早已去掉)。
2)第二趟遍历
将整个字符串完全翻转。

public class Solution {
    /**
     * @param s : A string
     * @return : A string
     */
    public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder(s.trim());
        //第一趟遍历
        for(int i = 0; i < sb.length();) {
            if(i+1 < sb.length() && sb.charAt(i) == ' ' && sb.charAt(i) == sb.charAt(i + 1)){//单词间连续空格,将多个空格减至一个
                sb.deleteCharAt(i+1);
                i++;
                continue;
            }else if(sb.charAt(i) != ' ') {//单词,将单词翻转
                int j = i;
                while(j+1 < sb.length() && sb.charAt(j + 1) != ' ') {//找到该单词最后一个字母
                    j++;
                }
                for(int k = 0; k < (j - i + 1)/2; k++) {//将单词翻转
                    char c = sb.charAt(k + i);
                    sb.setCharAt(k + i, sb.charAt(j - k));
                    sb.setCharAt(j - k, c);
                }
                i = j+1;
            }else {//一个空格
                i++;
            }
        }
        //第二趟遍历
        for(int i = 0; i < sb.length()/2; i++) {//从两端开始,前后互换
            char c = sb.charAt(i);
            sb.setCharAt(i, sb.charAt(sb.length() - 1 - i));
            sb.setCharAt(sb.length() - 1 - i, c);
        }
        return sb.toString();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值