【剑指offer】面试题58(1):翻转单词顺序

题目

牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。
同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。
例如,“student. a am I”。
后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。
Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

思路

先对整个句子翻转:
 “student. a am I” -> “I ma a .tneduts”
再对每个单词进行逐个翻转(标点符号和普通字母一样处理):
 “I ma a .tneduts” - > “I am a student.”

代码

public class _58_01_ReverseWordsInSentence {

    public String ReverseSentence(String str) {
        if(str == null || str.trim().length() <= 1)
            return str;
        char[] sentence = str.toCharArray();
        // 翻转整个句子 
        reverse(sentence, 0, sentence.length - 1);
        int low = 0;
        int high = 0;
        // 翻转每个单词
        while(low != sentence.length && high != sentence.length) {
            // 找到第一个非空格字符
            while(low != sentence.length && sentence[low] == ' ')
                ++low;
            if(low == sentence.length)
                break;
            // 找到low后面的第一个空格字符
            high = low + 1;
            while(high != sentence.length && sentence[high] != ' ')
                ++high;
            reverse(sentence, low, high - 1);
            low = high + 1;
        }
        return new String(sentence);
    }

    private void reverse(char[] str, int startIndex, int endIndex) {
        for(int low = startIndex, high = endIndex; low < high;
                ++low, --high) {
            char t = str[low];
            str[low] = str[high];
            str[high] = t;
        }
    }
}

测试

public class _58_01_Test {

    public static void main(String[] args) {
        test1();
        test2();
        test3();
    }


    private static void test1() {
        _58_01_ReverseWordsInSentence rwis = new _58_01_ReverseWordsInSentence();
        String s = rwis.ReverseSentence("student. a am I");
        MyTest.equal(s, "I am a student.");

        s = rwis.ReverseSentence("hello, peyton lin.");
        MyTest.equal(s, "lin. peyton hello,");

        // 两个空格 
        s = rwis.ReverseSentence("hello  ");
        MyTest.equal(s, "  hello");
    }

    private static void test2() {
        _58_01_ReverseWordsInSentence rwis = new _58_01_ReverseWordsInSentence();
        String s = rwis.ReverseSentence("a");
        MyTest.equal(s, "a");

        s = rwis.ReverseSentence("abc");
        MyTest.equal(s, "abc");

        s = rwis.ReverseSentence("");
        MyTest.equal(s, "");
    }

    private static void test3() {
        _58_01_ReverseWordsInSentence rwis = new _58_01_ReverseWordsInSentence();
        String s = rwis.ReverseSentence(null);
        System.out.println(s);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值