有关字符串练习题整理

不是最优解,基于自己能够理解的解法写,主要记录自己第一次刷力扣自己或者学习别人的答题思路

一、最长公共前缀

解题思路:先去匹配两个字符串中共同字符串,再去匹配其他的字符串即可

    public String longestCommonPrefix(String[] strs) {
        String temp = strs[0];
        for(int i = 1 ; i < strs.length; i ++){
            int j = 0;
            int count = Math.min(temp.length(),strs[i].length());
            for(; j < count; j++){
                if(temp.charAt(j) != strs[i].charAt(j)){
                    break;
                }
            }
            temp = temp.substring(0,j);
        }
        return temp;
    }

 二、最后一个单词的长度

解题思路:虽然可以上来就trim,split、length,思考了一下可以向前遍历

    public int lengthOfLastWord(String s) {
        s = s.trim();
        if(s.length() == 1){
            return 1;
        }
        int count = 0;
        for(int i =  s.length()-1; i > -1 ; i--){
            if(s.charAt(i) == ' '){
               break;
            }
            count++;
        }
        return count;
    }

三、反转字符串里的单词

思路一:使用split,然后找个栈,放进去 再出栈,但是属于O(2n)了=-=

    public String reverseWords(String s) {
        s = s.trim();
        String[] s1 = s.split(" ");
        Stack<String> stack = new Stack<>();
        for(int i = 0 ; i < s1.length; i++){
            stack.push(s1[i]);
        }
        StringBuffer sb = new StringBuffer();
        while(!stack.empty()){
            sb.append(" "+stack.pop());
        }
        return sb.toString().trim();
    }

思路二:前序遍历,使用双指针来截取字串、在append即可

    public String reverseWords2(String s) {
        int left = s.length() - 1;
        int right = s.length() - 1;
        StringBuffer res = new StringBuffer();
        while(left > -1) {
            //去掉多余空格
            while (left >= 0 && s.charAt(left) == ' ') {
                left--;
            }
            right = left; //确定字串结尾
            //找到字串起始
            while(left >= 0 && s.charAt(left) != ' '){
                left--;
            }
            res.append(s.substring(left + 1, right + 1));
            //一个单词之后添加一个空格
            res.append(' ');
        }
        return res.deleteCharAt(res.length() - 1).toString();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值