zoukankan      html  css  js  c++  java
  • LeetCode524-通过删除字母匹配到字典里最长单词

    给你一个字符串 s 和一个字符串数组 dictionary 作为字典,找出并返回字典中最长的字符串,该字符串可以通过删除 s 中的某些字符得到。

    如果答案不止一个,返回长度最长且字典序最小的字符串。如果答案不存在,则返回空字符串。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    ------------------------------------------------------------------------------------------------

    s可以通过删除某些字符得到字典中的值,换个思路想,只要s中包含字典中字符串(设为target)的所有字符,并且先后顺序一样,则s必定可以删除其中在target没有出现的字符,使得剩下的字符串可以与target相匹配  ---->可以用双指针去判断target中的字符是否都在s中出现;

    public String findLongestWord(String s, List<String> dictionary) {
            String res = ""; //存储最终的结果
            for (String target : dictionary) {
                int l1 = res.length(), l2 = target.length();
                /**
                 * 如果取出来的字符串的长度比当前存储的结果的长度要小,则可直接跳过
                 * 如果长度相同,但取出来的字符串在字典序更大,则可直接跳过
                 */
                if (l1 > l2 ||(l1 == l2 && res.compareTo(target)<0)){
                    continue;
                }
                if (isSubString(s, target)){
                    res = target;
                }
            }
            return res;
        }
    
        public boolean isSubString(String s, String target){
            int i = 0, j = 0;
            while (i < s.length() && j < target.length()){
                if (s.charAt(i) == target.charAt(j))
                    j++;
                i++;
            }
            return j == target.length();
        }
  • 相关阅读:
    无服务器架构(Faas/Serverless)
    Cookie中的sessionid与JSONP原理
    requestAnimationFrame
    JS函数的防抖和节流
    JS 中的广度与深度优先遍历
    堆、栈和队列
    Java除法和js
    selected
    找jar包
    编辑器替换操作
  • 原文地址:https://www.cnblogs.com/WakingShaw/p/14981173.html
Copyright © 2011-2022 走看看