1. 程式人生 > 其它 >【Leetcode】748. Shortest Completing Word

【Leetcode】748. Shortest Completing Word

技術標籤:# 棧、佇列、串及其他資料結構leetcode演算法字串

題目地址:

https://leetcode.com/problems/shortest-completing-word/

給定一個長 n n n的字串 s s s和一個英文小寫單詞陣列 A A A,找到 A A A中最短的包含了 s s s中所有英文字母的子串(不區分大小寫,但次數要考慮)。如果有若干個長度相同的答案,則返回第一個出現的。

程式碼如下:

public class Solution {
    public String shortestCompletingWord(String licensePlate, String[
] words) { int[] count = new int[26]; for (int i = 0; i < licensePlate.length(); i++) { char ch = licensePlate.charAt(i); if (Character.isLetter(ch)) { count[Character.toLowerCase(ch) - 'a']++; } } String res =
""; for (String word : words) { int[] curCount = new int[26]; for (int i = 0; i < word.length(); i++) { curCount[word.charAt(i) - 'a']++; } if (!check(count, curCount)) { continue; }
if (res.isEmpty() || word.length() < res.length()) { res = word; } } return res; } private boolean check(int[] count, int[] curCount) { for (int i = 0; i < 26; i++) { if (curCount[i] < count[i]) { return false; } } return true; } }

時間複雜度 O ( l s + n l ) O(l_s+nl) O(ls+nl) l l l A A A中最長單詞長度,空間 O ( 1 ) O(1) O(1)