Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
public class Solution {
public String reverseWords(String s) {
String res="";
//char[] tmp = new char[s.length()];
int i = 0;
int start = 0;
int end = 0;
while(i < s.length()){
while( i < s.length() && s.charAt(i) == ' '){
i ++;
}
start = i;
while(i < s.length() && s.charAt(i) != ' '){
i ++;
}
end = i - 1;
if(end >= start){//start~end就是一个word
res = s.substring(start,end+1) + " " + res;
}
i++;
}
return res.trim();
}
}
Runtime: 516 ms
public class Solution {
public String reverseWords(String s) {
String res="";
String[] tmp = s.split(" ");
for(int i = tmp.length - 1 ; i > -1 ; i --){
if(!tmp[i].equals("")){//注意不能使用==
res = res + " " + tmp[i] ;
}
}
return res.trim();
}
}
Runtime:
716 ms
stringbuffer
public class Solution {
public String reverseWords(String s) {
int start=0;//单词的开头
int end=s.length()-1;//最后一个单词的结尾
while(start<=s.length()-1&&s.charAt(start)==' '){//跳过开头的空格
start++;
}
while(end>=0&&s.charAt(end)==' '){//跳过结尾的空格
end--;
}
if(start>end) return "";
StringBuffer result= new StringBuffer();
while(start<=end){
StringBuffer word=new StringBuffer();
while(start <= end && s.charAt(start)!=' '){
word.append(s.charAt(start));
start++;
}
if(!word.equals("")) {
if(result.length() == 1){
result.insert(0,word);
}else{
result.insert(0,word+" ");
}
}
while(start <= end && s.charAt(start)==' ') start++;
}
return result.toString().trim();
}
}
Runtime: 444 ms
对于经常性修改字符串来说,可以考虑StringBuilder/StringBuffer
java.lang.StringBuilder
增加
append(char[])
append(char[],offset,len)
append(v) //将基本类型追加到stringbuffer之后
insert(offset,char[])
insert(offset,string)
删
delete(startIndex,endIndex)
deletecharAt(index)
改
setCharAt(index,c)
replace(startIndex,endIndex,string)//用string替换startIndex~endIndex-1
查
charAt(index)
substring(startIndex)//注意是小写的s
substring(start,end)//返回start到end-1
其他
length()
setLength()
String
比较
equals(string) //比较相等的时候
equalsIgnoreCase(string)
compareTo(string)//返回大于0或小于0或等于0
compareToIgnoreCase(string)
startsWith(string)
endsWith(string)
字符串长度,字符以及组合
length()
charAt(index)
concat(String)//连接
子串
substring(beginIndex) 获取beginIndex开始的子串
substring(beginIndex,endIndex) //返回begin~end-1之间的子串
替换,转换,分割
toLowerCase()
toUpperCase()
trim()
replace(oldchar,newchar)//用newchar替换所有的oldchar
replaceFirst(oldstring,newstring)//新字符串替换这个字符串中第一个匹配的子串
replaceAll(oldstring,newstring)//替换所有的
split()
matches(regix)
注意:以上的替换函数中的老字符串都可以使用正则表达式来表示
如:“a+b$#c”.replaceAll("[$+#]","NNN");
找出某个字符或者子串
indexOf(char)
indexOf(char,fromIndex)
indexOf(string)
indexOf(string,fromIndex)
lastIndexOf(char)
类似indexOf的重载函数
字符数值替换成字符串(静态方法)
valueOf(char)
valueOf(char[])
valueOf(double)
valueOf(float)
valueOf(int)
valueOf(long)
valueOf(boolean)