今天做了一道leedcode的题,感觉还好,题目是:
Reverse Words in a String14/03/05:
因为在之前在cc150里做过字符串的翻转,感觉很简单,把字符串用" "切开翻转连接就行了,可是这道题有不同问题,比如输入的是“ a x ”,就需要处理空格的问题。
我采用的方法是把每个字符加入string数组然后从前往后读,同时把最终的字符串从后往前接,遇到空格是进行处理,代码是:
public static String reverseWords4(String s) {
String[] a = s.split("");
int num = a.length;
String f = ""; // save final string
String b; // save temp string
b = "";
int pp=0; //signal
String tp=""; // save temp string
for(int i=0;i<num;i++){
//check if the char is " "
if(a[i].equals(" ")) {
f=b+f; //if yes, adding b to the front of f
if( !(b.equals(""))){
tp = f; //if b is not null, we need to add " ". But if there is no char after this,
f=" "+f; //we have to delete all " ". So I set pp and tp to save the copy of f at this time.
pp = 1;
}
b="";
continue;
}
//if not, adding char to b and cleaning tp and pp
b = b + a[i];
tp="";
pp=0;
//System.out.println("4"+pp+"5");
}
if(pp==1)return tp; //means the last several chars are " ", we need to return copy of f
if(!(a[num-1].equals(" ")))return b+f;
return f;
}
时隔一年,这次使用了两个指针直接扫字符串
public class Solution {
public String reverseWords(String s) {
if ( s.equals(""))
return s;
String res = "";
int start = 0;
int i=0;
for (i=0; i<s.length(); ){
if (s.charAt(i) == ' '){
if(start == i){
i++;
start++;
}else{
res = s.substring(start,i) + " "+ res;
i++;
start = i;
}
}else{
i++;
}
}
if (start != i)
res = s.substring(start,i) + " "+ res;
if (res.length() == 0)
return res;
return res.substring(0,res.length()-1);
}
}