leedcode做题总结,题目Reverse Words in a String14/03/05

今天做了一道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);
    }
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值