151. Reverse Words in a String
来源:互联网 发布:毕向东java全套视频 编辑:程序博客网 时间:2024/06/08 04:55
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the”.
按单词反转字符串 按照空格分割单词 重新倒序拼接就可以了
public String reverseWords(String s) { String[] array = s.split(" "); StringBuilder res = new StringBuilder(); for(int i=array.length-1; i>=0; i--) { if(array[i].isEmpty()) continue; res.append(array[i]); res.append(" "); } if (res.length() == 0) return res.toString(); else return res.toString().substring(0, res.length()-1); }
对应的
186. Reverse Words in a String II 增加了一个限制
Could you do it in-place without allocating extra space?
要求不额外开辟空间 感觉不是很好想 类似
48. Rotate Image http://blog.csdn.net/daimingyang123/article/details/78747262
这种reverse或者rotate 并要求in-place的 多想想两步完成
public void reverseWords(char[] s) { // Three step to reverse // 1, reverse the whole sentence reverse(s, 0, s.length - 1); // 2, reverse each word int start = 0; int end = -1; for (int i = 0; i < s.length; i++) { if (s[i] == ' ') { reverse(s, start, i - 1); start = i + 1; } } // 3, reverse the last word, if there is only one word this will solve the corner case reverse(s, start, s.length - 1);}public void reverse(char[] s, int start, int end) { while (start < end) { char temp = s[start]; s[start] = s[end]; s[end] = temp; start++; end--; }}
阅读全文
0 0
- LeetCode 151. Reverse Words in a String
- LeetCode 151. Reverse Words in a String
- [LeetCode]151.Reverse Words in a String
- 151. Reverse Words in a String
- [leetcode] 151.Reverse Words in a String
- Leetcode-151.Reverse Words in a String
- Leetcode 151. Reverse Words in a String
- 151. Reverse Words in a String
- 151. Reverse Words in a String
- 151. Reverse Words in a String
- [leetcode]151. Reverse Words in a String
- 151. Reverse Words in a String
- 151. Reverse Words in a String
- LeetCode 151. Reverse Words in a String
- Leetcode 151. Reverse Words in a String
- 151. Reverse Words in a String
- LeetCode *** 151. Reverse Words in a String
- LeetCode-151.Reverse Words in a String
- javascript中substring()、substr()、slice()的区别
- ionic Camera插件的使用(头像上传)
- js打造自动换肤系统
- [React]组件的生命周期
- 【知了堂学习笔记】_Jquery基础知识之DOM操作(二)
- 151. Reverse Words in a String
- 类训练-学生管理实现
- git常用命令小归宗
- https原理:证书传递、验证和数据加密、解密过程解析
- AlexNet、GoogLeNet、VGGNet、ResNet对比
- [总结]视音频编解码技术零基础学习方法
- 继承训练
- RadioButton 如何做到页面的显示和切换
- Maven深入学习(五)- dependencies与dependencyManagement的区别