面试之基础算法题:给定字符串,保持单词的顺序不变,倒序输出

面试题

给定字符串,保持单词的顺序不变,倒序输出。
如输入是"I am a professional java developer."
倒序输出的期望结果是这样的:“developer java professional a am I.”.

package algorithm.interview;

/**
 * Author: Johnny
 * Date: 2018/5/13
 * Time: 0:32
 */
public class ReverseString {
    public static void main(String[] args) {
        System.out.println(reverse1("This is a silly interview question."));
    }

	//思路
    private static String reverse(String input) {
        String words[] = input.split(" ");
        StringBuilder str = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--) {
            str.append(words[i]).append(" ");
        }
        return str.toString();
    }
	
	//完全实现期望的效果的输出
    private static String reverse1(String input) {
        String words[] = input.substring(0, input.length() - 1).split(" ");
        StringBuilder str = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--) {
            str.append(" ").append(words[i]);
        }
        return str.append(".").toString().trim();
    }
}

你可能感兴趣的:(java,面试)