Leetcode-Reverse Words in a String -java
2014-05-19 18:57
375 查看
题目:
Given an input string, reverse the string word by word.
For example,
Given s = "
return "
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.利用String split() 提取出每个单词
2.对于前缀“ ”和后缀“ ”进行处理
PS:
“” 为empty String对象,分配一个空的内存空间;
null 为空对象不分配内存空间;
String[] array = “ ”.split(" ");
array.length = 0;
isEmpty(“ ”) is false;
array.length;
StringBuffer.length(); String.length();
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.
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.利用String split() 提取出每个单词
2.对于前缀“ ”和后缀“ ”进行处理
public class Solution { public String reverseWords(String s) { if(s == null || "".equals(s)){ return ""; } String[] array = s.split(" "); StringBuffer sb = new StringBuffer(); for(int i = array.length - 1; i >=0; i--){ if(!"".equals(array[i])){ sb.append(array[i]).append(" "); } } return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1).toString(); }//reverseWords }
PS:
“” 为empty String对象,分配一个空的内存空间;
null 为空对象不分配内存空间;
String[] array = “ ”.split(" ");
array.length = 0;
isEmpty(“ ”) is false;
array.length;
StringBuffer.length(); String.length();
相关文章推荐
- Reverse Words in a String leetcode java
- 【LeetCode-面试算法经典-Java实现】【151-Reverse Words in a String(反转字符串中的单词)】
- [leetcode]151. Reverse Words in a String@Java解题报告
- 【LeetCode刷题Java版】Reverse Words in a String
- Java for LeetCode 151 Reverse Words in a String
- java中leetcode之Reverse Words in a String
- 【Leetcode】Reverse Words in a String JAVA
- leetcode 151 Reverse Words in a String java 算法
- leetcode:151Reverse Words in a String java实现
- 【leetcode】Reverse Words in a String(Java)
- leetcode-java-151. Reverse Words in a String
- LeetCode|Reverse Words in a String-java
- leetcode JAVA Reverse Words in a String 难度系数2-3?最新题151
- leetcode JAVA Reverse Words in a String 难度系数2-3?最新题151
- 【LeetCode刷题Java版】Reverse Words in a String
- Reverse Words in a String ---leetcode 我的java题解
- [Leetcode][JAVA] Reverse Words in a String
- LeetCode:Reverse Words in a String (Java)
- [LeetCode] Reverse Words in a String
- LeetCode Reverse Words in a String