leetcode_Reverse Words in a String
来源:互联网 发布:php网站如何搭建 编辑:程序博客网 时间:2024/05/07 15:34
描述:
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.
思路:
1.trim()+去除串内多余的空格
2.将串内每个单词反转
3.将整个句子反转
代码:
public String reverseWords(String s) {s=s.trim();if(!s.equals("")){char arr[]=s.toCharArray();int index=1;for(int i=1;i<arr.length;i++){if(arr[i-1]==arr[i]&&arr[i]==' ')continue;elsearr[index++]=arr[i];}s=new String(arr,0,index);}else {return "";}StringBuilder sBuilder=new StringBuilder(s);char ch;int i=0,j=s.length()-1;int start=0,end=0;for(i=0;i<sBuilder.length();i++){start=i;while(sBuilder.charAt(i)!=' '&&i!=j)i++;end=i;if(end!=j)end--;while(start<end){ch=sBuilder.charAt(start);sBuilder.setCharAt(start, sBuilder.charAt(end));sBuilder.setCharAt(end, ch);start++;end--;}}sBuilder.reverse(); return sBuilder.toString(); }
0 0
- Leetcode_Reverse-Words-in-a-String
- LeetCode_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.
- 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
- Android开发之MdiaPlayer详解
- IOS 8 定位
- Lucene学习总结之一:全文检索的基本原理
- oracle parameter parallel_max实验
- Atom编辑器折腾记_(5)记住上一次打开的目录及浏览器预览功能实现
- leetcode_Reverse Words in a String
- Caused by: java.lang.InstantiationException
- iOS分辨率的那些事儿
- Linux下read和write的正确用法
- 作为立志于在开发道路上越走越远的我们应该会些什么
- Android项目使用Ant打包,自动生成build.xml
- "display: inline-block;"不兼容IE6
- Linux中ELF格式文件介绍
- java面试中遇到的两道String的面试题