[Lintcode]Reverse Words in a String
来源:互联网 发布:企业管理优化建议 编辑:程序博客网 时间:2024/06/08 12:15
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
两个指针,每次遇到空格进行判定是否插入新单词并初始化index。Leading space会由于start=-1而避免。多个空格的情况同样。 最后处理tailing space即可。
public class Solution { /** * @param s : A string * @return : A string */ public String reverseWords(String s) { StringBuilder res = new StringBuilder(); char[] array = s.toCharArray(); int start = -1, end = -1; for(int i = 0; i < array.length; i++) { char c = array[i]; if(c == ' ') { //detected a word if(start != -1) { end = i; res.insert(0, s.substring(start, end)); res.insert(0, " "); //re-init start = -1; end = -1; } } else { if(start == -1) start = i; } } if(start != -1) res.insert(0, s.substring(start));//add last word when have not trailing space if(res.length() > 0 && res.charAt(0) == ' ') res.deleteCharAt(0);//remove leading space return res.toString(); }}
0 0
- [Lintcode]Reverse Words in a String
- [Lintcode]Reverse Words in a String
- 【LintCode】Reverse Words in a String 翻转字符串
- 【LintCode】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
- 第一行代码-9.3 服务的基本用法
- 简单排序方法
- 如何将eclipse项目和svn关联(从服务器取项目)
- leetcode-81-Search in Rotated Sorted Array II
- 简单递归
- [Lintcode]Reverse Words in a String
- UVA 294(p344)----Divisors
- 喊啥--历史记录
- Bridges and Frame Filtering
- mycat mysql主从配置实现读写分享篇
- Numpy——ndarray对象(2):数组存取和多维数组
- Intel处理器MSR学习
- 【LeetCode】268. Missing Number
- poj 3280 Cheapest Palindrome