剑指offer第二版-58.翻转单词顺序

本系列导航:剑指offer(第二版)java实现导航帖

面试题58:翻转单词顺序

题目要求:
输入一个英文句子,翻转单词顺序,单词内字符不翻转,标点符号和普通字母一样处理。例如输入输入“I am a student.”,则输出“student. a am I”。

解题思路:
首先字符串整体翻转,得到“.tneduts a ma I”;然后以空格作为分隔符进行切分,对于切分下来的每一部分再进行翻转,得到“student. a am I”。

package chapter6;

/**
 * Created with IntelliJ IDEA
 * Author: ryder
 * Date  : 2017/8/17
 * Time  : 16:01
 * Description:翻转字符串
 **/
public class P284_ReverseWordsInSentence {
    public static String reverse(String str){
        StringBuilder stringBuilder = new StringBuilder(str);
        reverseSubString(stringBuilder,0,stringBuilder.length()-1);
        int start = 0,end = stringBuilder.indexOf(" ");
        while (start<stringBuilder.length()&&end!=-1){
            reverseSubString(stringBuilder,start,end-1);
            start = end+1;
            end = stringBuilder.indexOf(" ",start);
        }
        if(start<stringBuilder.length())
            reverseSubString(stringBuilder,start,stringBuilder.length()-1);
        return stringBuilder.toString();
    }
    //翻转stringBuilder[start,end]
    public static void reverseSubString(StringBuilder stringBuilder,int start,int end){
        for(int i=start;i<=start+(end-start)/2;i++){
            char temp = stringBuilder.charAt(i);
            stringBuilder.setCharAt(i,stringBuilder.charAt(end-i+start));
            stringBuilder.setCharAt(end-i+start,temp);
        }
    }
    public static void main(String[] args){
        System.out.println(reverse("I am a student."));
    }
}

运行结果

student. a am I
    原文作者:ryderchan
    原文地址: https://www.jianshu.com/p/8a79f439e63d#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞