104.Reverse Words in a String
来源:互联网 发布:olafur arnalds 知乎 编辑:程序博客网 时间:2024/05/29 19:23
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.
click to show clarification.
Subscribe to see which companies asked this question
与剑指offer上的面试题42翻转单词序列类似,但是比那道题目多了限制条件。
并且要首先去掉str开头和结尾的空格,并且把字符串中间的多个空格用一个空格表示。这点与剑指offer上的不同。所以在开始的时候要把空格做处理。
/** * Given s = "the sky is blue", * return "blue is sky the". * 并且要首先去掉str开头和结尾的空格,并且把字符串中间的多个空格用一个空格表示。这点与剑指offer上的不同。 * 所以在开始的时候要把空格做处理。 */ public String reverseWords(String str){ str = str.replaceAll("\\s{1,}", " "); if(str.length()<=0){ return ""; } if(str.charAt(0)==' '){str = str.substring(1); } if(str.length()<=0){ return ""; } if(str.charAt(str.length()-1)==' '){ str = str.substring(0,str.length()-1); } return reverseWordsFromOffer(str); } public String reverseWordsFromOffer(String str) { int len = str.length(); if(len <= 0){ return str; } /*首先反转整个句子*/ String s1 = Reverse(str,0,len-1); /*逐个反转每个单词*/ for(int i=0;i<len;i++){ int low = i; while(i<len && s1.charAt(i)!=' '){ i++; } int high = i-1; if(low == high){/*长度为1的单词不需要反转*/ }else{ s1 = Reverse(s1,low,high); } } return s1; } String Reverse(String s,int start ,int end){int len = s.length()-1;String s1 = s.substring(0,start);String s2 = s.substring(end+1);StringBuffer sb = new StringBuffer();for(int j=end;j>=start;j--){sb.append(s.charAt(j));}return s1 + new String(sb)+s2;}
细节决定成败,需要多多注意细节,认真考虑问题!!!!!!!!!!!!!!!!!!!!!
0 0
- 104.Reverse Words in a String
- Reverse words in a string.
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- Reverse Words in a String
- 读取系统通讯录信息的时候出错:.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow
- Ogre学习笔记1(你的第一个场景)
- matlab-code folding功能 将某些行的代码折叠起来方便查看
- MyEclipse使用依赖项目在发布项目时报ClassNotFound
- 购买计划
- 104.Reverse Words in a String
- HashMap的实现原理
- 收集的48个Shell脚本小技巧
- iOS中 本地通知/本地通知详解 韩俊强的博客
- Java泛型实例
- List转树形数据,供tree使用
- Android 系统稳定性 - ANR(一)
- Linux 常用命令3-- 目录操作rmdir 和 rm
- MyBatis入门1--初识Mybatis