首页 > 代码库 > LeetCode-Reverse Words in a String[AC源码]
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 Submissions10 * Given an input string, reverse the string word by word.11 * 12 * For example13 * 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 LiuWei25 * @Date 2014年8月15日下午7:48:4826 * @Mail nashiyue1314@163.com 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 space50 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 space72 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 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。