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;
        }
    }
全部评论

相关推荐

点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-03 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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