LeetCode-Reverse Words in a String[AC源码]

 1 package com.lw.leet1;

 2 

 3 import java.util.Stack;

 4 

 5 /**

 6  * @ClassName:Solution

 7  * @Description:

 8  *         Reverse Words in a String 

 9  *         Total Accepted: 26194 Total Submissions: 187094 My Submissions

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

11  * 

12  *         For example

13  *             Given s = "the sky is blue"

14  *             return "blue is sky the".

15  * 

16  *         Clarification:

17  *             What constitutes a word?

18  *             A sequence of non-space characters constitutes a word.

19  *         Could the input string contain leading or trailing spaces?

20  *             Yes. However, your reversed string should not contain leading or trailing spaces.

21  *         How about multiple spaces between two words?

22  *             Reduce them to a single space in the reversed string.

23  * 

24  * @Author LiuWei

25  * @Date 2014年8月15日下午7:48:48

26  * @Mail [email protected] 

27  */

28 public class Solution {

29     

30     public String reverseWords(String word){

31         Stack<String> sstack = new Stack<String>();

32         int flag = 0;

33         for(int i= 0; i<word.length(); i++){

34             while(i<word.length() && word.charAt(i)==' '){

35                 i++;

36             }

37             flag = i;

38             while(i<word.length() && word.charAt(i)!=' '){

39                 i++;

40             }

41             if(flag != i){

42                 sstack.push(word.substring(flag, i));

43             }

44         }

45         String res = "";

46         while(!sstack.isEmpty()){

47             res += sstack.pop()+" ";

48         }

49 //        The input string which is made up of space

50         if(res.length()==0){

51             return "";

52         }

53         return res.substring(0, res.length()-1);

54     }

55     

56     public String reverseWords2(String word){

57         String res ="";

58         int flag = 0;

59         for(int i= 0; i<word.length(); i++){

60             while(i<word.length() && word.charAt(i)==' '){

61                 i++;

62             }

63             flag = i;

64             while(i<word.length() && word.charAt(i)!=' '){

65                 i++;

66             }

67             if(flag != i){

68                 res = word.substring(flag, i)+" "+res;

69             }

70         }

71 //        The input string which is made up of space

72         if(res.length()==0){

73             return "";

74         }

75         return res.substring(0, res.length()-1);

76     }

77     

78     public static void main(String[] args){

79         Solution s = new Solution();

80         System.out.println(s.reverseWords2("   hello world    "));

81     }

82 }

 

你可能感兴趣的:(LeetCode)