c++ string 前缀_每日一题:最长公共前缀

每日一题:最长公共前缀

3b0d8fd7a0f8ef0bc1fe0993575d8c35.png
image-20210113221044548

开始

这题比昨天的罗马数字我感觉难度差不多

但是写起来却繁琐了一些,不那么有美感

class Solution {
    public static String longestCommonPrefix(String[] strs) {
        int strsLen = strs.length;
        if (strsLen == 0) { return ""; }
        char[][] css = new char[strsLen][200];
        for (int i = 0; i             String s = strs[i];
            for (int j = 0; j                 css[i][j] = s.charAt(j);
            }
        }

        char[] cs = new char[200];
        for (int i = 0; i 100; i++) {
            char target = css[0][i];
            boolean allSame = true;
            for (int j = 0; j                 char curr = css[j][i];
                if (curr == target) {
                    continue;
                }
                allSame = false;
            }
            if (allSame) {
                cs[i] = target;
            } else {
                return c2s(cs);
            }
        }

        return c2s(cs);
    }

    private static String c2s(char[] cs) {
        StringBuilder sb = new StringBuilder();
        for (char c : cs) {
            if (c != '\u0000') {
                sb.append(c);
                continue;
            }
            return sb.toString();
        }
        return sb.toString();
    }
}

大体思路是分两个步骤

第一步:把输入用二维字符数组存储

第二步:从横向遍历转为纵向遍历

那么就可以把字符一个个拉出来比较异同了,直到发现不同就return了

这里学到个新知识

原来char的初始值是'\u0000',开始没处理,执行一直无法通过,后来只好祭出StringBuilder拼接大法了

老规矩,秀一下效率哈哈~

39f6284ff7c9ea26a0c6e94e37fcd0d9.png
image-20210113221806457

这次还是比较满意der~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值