025 反转句子

1.题目

  假设有一个句子you are good ,反转句子为good are you。

  不能使用split等函数。

2.思路

  这里可以使用Stack。

3.程序

 1 import java.util.Stack;
 2 
 3 public class word {
 4     //main函数,方面测试
 5     public static void main(String[] args){
 6         String str="what is your name";
 7         String result=reverseWord(str);
 8         System.out.println(result);
 9     }
10     //这是正式逻辑处理
11     public static String reverseWord(String str){
12         Stack<String> stack=new Stack();
13         String temp="";
14         for(int i=0;i<str.toCharArray().length;i++){
15             if(!(str.charAt(i)==' ')){
16                 temp+=str.toCharArray()[i];
17         }else{
18             stack.push(temp);
19             temp="";
20         }
21     }
22         stack.push(temp);
23     //弹出栈中单词
24     String result="";
25     int size=stack.size();
26         for(int i=0;i<4;i++){
27             result=result+stack.pop()+" ";
28         }
29         return result;
30 }
31 
32 }

猜你喜欢

转载自www.cnblogs.com/juncaoit/p/10504159.html