1. 程式人生 > >將一個句子逆序

將一個句子逆序

/**
 * @Task:Given an input string,reverse the string word by word.
 * For example,
 * Given s="my name is black",
 * return "black is name my".
 */

package black.algorithm.reverse;

import java.util.Stack;

public class Reverse {

    public static String toReverse(String in){

        //存放單詞的棧
        Stack<Character> word=new
Stack<Character>(); //存放句子的棧 Stack<Character> sentence=new Stack<Character>(); //存放逆序後的字串 StringBuilder out=new StringBuilder(); //字串索引 int i=0; while(i<=in.length()){ //遇到空格 if(i==in.length()||in.charAt(i)==' '
){ if(!word.isEmpty()){ //將word棧中一個單詞轉移到sentence棧中 while(!word.isEmpty()){ sentence.push(word.pop()); } //sentence棧中新增空格,即為單詞之間新增空格 if(!sentence.isEmpty()){ sentence.push(' '
); } } }else{ //將給定字串中的字元一個一個放進棧中 word.push(in.charAt(i)); } //字串索引自增 i++; } while(!sentence.isEmpty()){ out.append(sentence.pop()); } return out.toString(); } public static void main(String[] args) { String input="my name is black"; String output=toReverse(input); System.out.println(output); } }

執行結果:

這裡寫圖片描述