LeetCode最长子序列

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

图片说明
这个题的解法:

    public String findLongestWord(String s, List<String> d) {
        String result = "";
        // 遍历字典里的字符串
        for (String dic : d) {
            int l1 = result.length();
            int l2 = dic.length();
            // 如果目前最长子串的长度大于当前遍历到的字典中的字符串,则无需再判断是否是子串
            if (l1 > l2 || (l1 == l2 && result.compareTo(dic) < 0)) {
                // result.compareTo(dic)返回的是result - dic的码值,即比较字典顺序
                continue;
            }
            // 如果字典中的子串dic是s的子串,则当前最长子串为
            if (isSubstr(dic, s)) {
                result = dic;
            }
        }
        return result;
    }

判断是否是子串的程序:

// s是否是target的子串
    private boolean isSubstr(String s, String target) {
        int i = 0;
        int j = 0;
        // 遍历s和target
        while (i < s.length() && j < target.length()) {
            // 如果相等,则s的指针也移动一位
            if (s.charAt(i) == target.charAt(j)) {
                i++;
            }
            // target的指针移动一位
            j++;
        }
        // 有一个指针到头了
        if (i == s.length()) {
            // 如果此时i到头, 则是子串
            return true;
        } else {
            // 如果i没到头,j却到头了,则不是子串
            return false;
        }
    }
全部评论

相关推荐

北漂的牛马人:211佬,包进的,可能是系统问题
点赞 评论 收藏
分享
风中翠竹:真的真的真的没有kpi。。。面试官是没有任何kpi的,捞是真的想试试看这个行不行,碰碰运气,或者是面试官比较闲现在,没事捞个人看看。kpi算HR那边,但是只有你入职了,kpi才作数,面试是没有的。
双非有机会进大厂吗
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-27 15:19
简历上能写3个月吗?
码农索隆:大胆写,主要你能把实习经历包装好,可以看一下我这篇帖子https://www.nowcoder.com/share/jump/4888395581180798063
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务