LeetCode | Reverse Words in a String

来源:互联网 发布:韩国网络直播间 编辑:程序博客网 时间:2024/06/06 07:05

题目:

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

注意:通过从后向前遍历,遇到空格,就将后面的所有字符复制到StringBUffer中,并用一个int变量记录此次空格的索引值,作为下一次遍历的开始处。

代码如下:

package com.LeetCode.cheng1;import java.util.Scanner;import java.util.Stack;public class Reverse_Words_in_a_String {public static void main(String[] args) {// TODO Auto-generated method stub Scanner sc = new Scanner(System.in);          System.out.println("请输入:");          String word = sc.nextLine();          StringBuffer sb = new StringBuffer();         int endIndex = word.length()-1;         for(int i = word.length()-1; i>=0; i--){         if(word.charAt(i) ==' '||i == 0){         sb.append(word.substring(i, endIndex+1));                  endIndex = i;         }         }        System.out.println(sb);}}


0 0
原创粉丝点击