【Leetcode】Reverse word in a string
来源:互联网 发布:mac版千牛 编辑:程序博客网 时间:2024/06/06 02:00
【题目】
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
click to show 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.
【题解】
1.遇到空格就跳过,第一个不是空格的元素,位置用pos记录。
2. 即pos之后,继续,只要不是空格,i++
3.当遇到的是第一个单词,即res长度为0时,直接添加,否则,添加“ ”,然后再在前面添加新的单词,达到reverse的效果,res= s.substring(pos,i),+res;注意顺序
4.i-- 因为在检查是否空格那里i++了
注意:substring函数,start是包含的,而end的标是达不到的;
用+重新赋值的好处是可以直接把新的单词调整到最前面,但是这样的做法是不是要耗费的空间比较大。得是单词数目+空格数目。基本是2倍单词数量。
【代码】
public static String solution(String s){String res= "";for(int i=0;i<s.length();i++){if(s.charAt(i)==' ') continue;int pos=i;while(i<s.length()&&s.charAt(i)!=' ') i++;if(res.length()>0) res=" "+res;res=(s.substring(pos,i))+res;i--;}return res;}
【官方题解】
One simple approach is a two-pass solution: First pass to split the string by spaces into an array of words, then second pass to extract the words in reversed order.
We can do better in one-pass. While iterating the string in reverse order, we keep track of a word’s begin and end position. When we are at the beginning of a word, we append it.
public class Solution { public String reverseWords(String s) { String[] a=s.trim().split("\\s+");StringBuilder res=new StringBuilder();for(int i=a.length-1;i>=0;i--){if(i==a.length-1)res.append(a[i]);else res.append(" ").append(a[i]);}return res.toString(); }}\\s+:
splitpublic String[] split(String regex)根据给定的正则表达式的匹配来拆分此字符串。 然后就要明确正则表达式的含义了:\\s表示 空格,回车,换行等空白符, +号表示一个或多个的意思,所以...
- reverse word in a string(leetcode)
- Reverse word in a string [leetcode]
- 【Leetcode】Reverse word in a string
- Leetcode: Reverse word in string
- Reverse Word in a String
- Reverse Word in a String(improve)
- Reverse every word 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
- Apache Commons-logging使用实例
- linux inode已满解决方法
- [: 3: y: unexpected operator问题
- 各种厉害的死循环代码
- 云资源汇总--- Hadoop/Storm/Spark/Openstack
- 【Leetcode】Reverse word in a string
- window.name实现跨域
- 给老板汇报技术规划的一些要点
- gcc中关于静态库和动态库使用 -转载
- 创建 Windows 身份验证登录名
- 017java Object类
- 进程同步的机制以及通讯方法
- 从零开始iOS8编程【iOS开发常用控件】
- Java TreeMap的排序(转)