每日算法:524. 通过删除字母匹配到字典里最长单词

192 阅读1分钟

难度:中等

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

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

解题思路

  • 遍历字符串数组,然后每个字符串数组里面的字符串与完整字符串进行对比;
  • 定义两个变量表示下标,然后一一对比,直到字符串已经遍历完了为止则为子字符串;

题解

public String findLongestWord(String s, List<String> dictionary) {
    String max = "";
    for (String subStr : dictionary) {
        if (isSubString(s, subStr) && (max.length() < subStr.length() || (max.length() == subStr.length() && max.compareTo(subStr) > 0))) {
            max = subStr;
        }
    }
    return max;
}

private boolean isSubString(String fullStr, String subStr) {
    int fullStrIndex = 0;
    int subStrIndex = 0;

    int fullLength = fullStr.length();
    int subLength = subStr.length();
    while (fullStrIndex < fullLength && subStrIndex < subLength) {
        if (fullStr.charAt(fullStrIndex) == subStr.charAt(subStrIndex)) {
            ++subStrIndex;
            if (subStrIndex == subLength) {
                return true;
            }
        }
        ++fullStrIndex;
    }
    return false;
}

测试

LongestWordInDictionaryThroughDeleting longestWordInDictionaryThroughDeleting = new LongestWordInDictionaryThroughDeleting();

@Test
public void test_withoutSort_case1() {
    String actual = longestWordInDictionaryThroughDeleting.findLongestWord("abpcplea", Arrays.asList("ale", "apple", "monkey", "plea"));
    Assertions.assertEquals("apple", actual);
}

@Test
public void test_withoutSort_case2() {
    String actual = longestWordInDictionaryThroughDeleting.findLongestWord("abpcplea", Arrays.asList("ale", "aplea", "apple", "plea"));
    Assertions.assertEquals("aplea", actual);
}

@Test
public void test_withoutSort_case3() {
    String actual = longestWordInDictionaryThroughDeleting.findLongestWord("abpcplea", Arrays.asList("ale", "apple", "aplea", "plea"));
    Assertions.assertEquals("aplea", actual);
}

@Test
public void test_withoutSort_case4() {
    String actual = longestWordInDictionaryThroughDeleting.findLongestWord("abpcplea", Arrays.asList("a", "b", "c"));
    Assertions.assertEquals("a", actual);
}

@Test
public void test_withoutSort_case5() {
    String actual = longestWordInDictionaryThroughDeleting.findLongestWord("abce", Arrays.asList("abe", "abc"));
    Assertions.assertEquals("abc", actual);
}