LeetCode题解 -- 双指针(524)

Longest Word in Dictionary through Deleting

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.

时间复杂度:O(M * N)
空间复杂度:O(1)

需要保证两个等长的符合条件的str中,取字典序最小的。也可以先对List中的元素排序(可能性能更好)

public String findLongestWord(String s, List<String> d) {
        int stringLen = s.length();
        int listLen = d.size();

        if(stringLen == 0 || listLen == 0)
            return "";
        String result = "";

        char[] charArray = s.toCharArray();
        int maxLen = 0;
        for(String str : d){
            int length = str.length();
            int i = 0;
            int j = 0;
            int count = 0;
            while(i < stringLen && j < length){
                if(charArray[i] == str.charAt(j)){
                    i++;
                    j++;
                    count++;
                }else{
                    i++;
                }
            }
            if(j == length){
                if(count > maxLen){
                    maxLen = count;
                    result = str;
                }else if(count == maxLen){
                    if(result == ""){
                        result = str;
                    }else if(!result.equals(str)){
                        result = getSmallestLex(result,str);
                    }
                }
            }
        }

        return result;
    }
    
    public String getSmallestLex(String A,String B){
        int length = A.length();
        int i = 0;
        int j = 0;
        while(i < length){
            if(A.charAt(i) < B.charAt(j)){
                return A;
            }else if(A.charAt(i) > B.charAt(j)){
                return B;
            }else{
                i++;
                j++;
            }
        }
        
        return A;
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值