首页 > 代码库 > leetcode 151. Reverse Words in a String --------- java
leetcode 151. Reverse Words in a String --------- java
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
倒序字符串。
注意使用BufferString,因为如果使用String的话,会多次建立对象,会很慢。
public class Solution { public String reverseWords(String s) { int len = s.length(); if( len == 0) return s; StringBuffer result = new StringBuffer() ; int end = len-1,start = 0; while( end >= 0 && s.charAt(end) == ‘ ‘) end--; if( end == -1) return result.toString(); while( start < len && s.charAt(start) == ‘ ‘) start++; int pos = end+1; for( int i = end ; i >= start ; i-- ){ if( s.charAt(i) == ‘ ‘) { result.append(s.substring(i+1,pos)); result.append(" "); while (i < end && s.charAt(i) == ‘ ‘) i--; i++; pos = i; } } result.append(s.substring(start,pos)); return result.toString(); } }
leetcode 151. Reverse Words in a String --------- java
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。