151. Reverse Words in a String
来源:互联网 发布:淘宝中差评处理 编辑:程序博客网 时间:2024/05/16 15:24
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.
Clarification:
What constitutes a word?
A sequence of non-space characters constitutes a word.
Could the input string contain leading or trailing spaces?
Yes. However, your reversed string should not contain leading or trailing spaces.
How about multiple spaces between two words?
Reduce them to a single space in the reversed string.
public class Solution { public String reverseWords(String s) { if (s == null) return null; char[] a = s.toCharArray(); int n = s.length(); reverse(a, 0, n-1); reverseWord(a, n); return cleanspace(a, n); } public void reverse(char[] a, int start, int end) { while (start < end) { char tmp = a[start]; a[start++] = a[end]; a[end--] = tmp; } } public void reverseWord(char[] a, int n) { int i = 0, j = 0; while (i < n) { while (i < j || i < n && a[i] == ' ') i++; while (j < i || j < n && a[j] != ' ') j++; reverse(a, i, j-1); } } public String cleanspace(char[] a, int n) { int i = 0, j = 0; while (j < n) { while (j < n && a[j] == ' ') j++; while (j < n && a[j] != ' ') a[i++] = a[j++]; while (j < n && a[j] == ' ') j++; if (j < n) a[i++] = ' '; } return new String(a).substring(0, i); }}
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
- 汇编输出文字
- 房卡麻将分析系列之"千里传音"
- java用Cors方式让Ajax可以跨域访问
- Myeclipse2016jsp中文乱码问题的解决方法
- 思考专注力
- 151. Reverse Words in a String
- Android Studio 新建或者导入项目出现"building gradle project info"一直卡住的解决方法
- 教育人们通过什么方法保护自己,通过什么方法制裁对方。
- C# -- delegate 与 event 解析
- love
- Ubuntu linux 环境基本使用
- 二、webpack的基本配置(1)
- 51Nod 1091 线段的重叠 (区间贪心
- POJ-3461 Oulipo