LeetCode刷题笔录Reverse Words in a String
来源:互联网 发布:互联网大会2017 知乎 编辑:程序博客网 时间:2024/06/06 02:52
https://oj.leetcode.com/problems/reverse-words-in-a-string/
我的做法是从后往前扫描,遇到空格就前进一个字符,直到不是空格为止。然后把不是空格的连续字符都放到一个buffer里,然后把这个buffer反序放到结果string里。结果string要加一个空格。
比如 i am legend. 先是buffer里放dnegel,然后反序这个buffer变成legend放到结果里
java的stringbuffer自带reverse()函数,不过我猜应该不能直接用吧,要自己写一个。
public class Solution { public String reverseWords(String s) { if(s == null || s.length() == 0) return ""; StringBuffer res = new StringBuffer(); int i = s.length() - 1; while(i >= 0){ while(i >= 0 && s.charAt(i) == ' ') i--; if(i == -1) break; if(res.length() != 0) res.append(" "); StringBuffer word = new StringBuffer(); while(i >= 0 && s.charAt(i) != ' '){ word.append(s.charAt(i)); i--; } String str = reverse(word.toString()); res.append(str); } return res.toString(); } public String reverse(String s){ char[] arr = s.toCharArray(); for(int i = 0; i < arr.length / 2; i++){ char temp = arr[i]; arr[i] = arr[arr.length -1 - i]; arr[arr.length - 1 - i] = temp; } return new String(arr); }}
0 0
- LeetCode刷题笔录Reverse Words in a String
- Leetcode - string - Reverse Words in a String
- Reverse words in a String leetcode
- [LeetCode]Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- Reverse Words in a String (LeetCode)
- LeetCode Reverse Words in a String Total
- LeetCode(151)Reverse Words in a String
- Reverse Words in a String -- LeetCode
- leetcode Reverse Words in a String
- LeetCode OJ:Reverse Words in a String
- LeetCode Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- [Leetcode] Reverse Words in a String
- Reverse Words in a String[LeetCode]
- LeetCode OJ :Reverse Words in a String
- Leetcode: Reverse Words in a String
- 【LeetCode】Reverse Words in a String
- 利用mybatis-generator自动生成JavaBean,mapping映射文件等
- Eclipse超级联想和alt+/ 联想的实现方法
- Error when using imshow on OS X
- auto的使用
- HDU2063(匈牙利算法)
- LeetCode刷题笔录Reverse Words in a String
- 用Github和Octopress搭建博客
- SQLite数据库拼写工具类
- 判断ios程序第一次启动
- Linux系统开机过程详解
- Hibernate工作原理及为什么要用?
- 常用知识点积累
- log4j.properties配置详解
- 单片机寄存器设置