LeetCode Solution, Medium, 1239. Maximum Length of a Concatenated String with Unique Characters
尋找最長的連接字串,其中字串符號皆唯一
Search for a command to run...
尋找最長的連接字串,其中字串符號皆唯一
No comments yet. Be the first to comment.
現在應該開始有很多人想要踏入軟體工程的領域,但在進入這個領域之前,覺得先了解一些名詞,可以在入門時更有方向也更知道要用什麼關鍵字去找尋有用的資訊。這篇文章就是想要幫助想要入門的人理解一些軟體工程裡的專有名詞。 作業系統 這一區塊主要解釋跟作業系統層面相關的名詞 英文中文解釋 Operation system 簡稱 OS | 作業系統 | 就是電腦的作業系統,是三大作業系統分別是:Linux、Windows、macOS | | Linux | | 自由和開放原始碼的 UNI...
現在開始因為 ChatGPT 的出現,各種 AI 助手的功能都跑出來了。想想自己用了許久的環境設定也應該要來重新審視和建立新的開發環境了,僅此紀錄我個人的環境配置步驟和設定。 環境前置步驟 還原 MacBook Pro 至全新環境 macOS(全部資料刪除) 設定好初始設定後,登入 Apple ID 進入 App Store 確定 macOS 版本和預設 APP 都更新到最新 macOS 版本 到系統設定調整所有設定至個人習慣的設定 三指拖移 觸控板手勢開啟 防火牆開啟 輸入法設定...
從 ChatGPT 問世到現在,有許許多多的文章和討論出來。先從最早的 Google 要完蛋了,到後來的工作要被取代了,工程師失業了。 我就比較沒有想要馬上出來評論一下,我喜歡讓子彈飛一會兒。跟討論一下我自己比較在意的討論點。 Google 為什麼慢了? 結論:因為他需要更小心 很多人說 Google 怎麼被微軟搶先了一步。剛開始 Bing 說要加上 AI 的時候大家都在說 Google 怎麼慢了。我就馬上跑去看 OpenAI 的網站,靠北呀啊就 Azure 贊助的。那當然在正式上線 ChatG...
囤積癖
607. Sales Person 題目敘述 SQL Schema > Create table If Not Exists SalesPerson (sales_id int, name varchar(255), salary int, commission_rate int, hire_date date) Create table If Not Exists Company (com_id int, name varchar(255), city varchar(255)...
Given an array of strings arr. String s is a concatenation of a sub-sequence of arr which have unique characters.
Return the maximum possible length of s.
Example 1:
Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique".
Maximum length is 4.
Example 2:
Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible solutions are "chaers" and "acters".
Example 3:
Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26
Constraints:
1 <= arr.length <= 161 <= arr[i].length <= 26arr[i] contains only lower case English letters.Hint 1:
You can try all combinations and keep mask of characters you have.
Hint 2:
You can use DP.
給一個 list 參數 arr,其中元素都是字串。要從中找出最長的字串組合。其中這個組合要符合的條件,就是其中的元素需要是唯一的字母。
大部分的解法,會用到位元運算子 <<、&、>>。有的則是單純的使用演算法比對長度的方式。個人覺得最漂亮的方式是 Swift 的解法。
使用兩個迴圈處理做 Dynamic programming,第一層去遍歷 arr 的元素,去跟另一層迴圈遍歷的 list combos 做判斷。如果 arr 和 combos 遍歷的元素相加後,是唯一的話,則儲存到 combos,並且跟最大值最比較。
Runtime Best
class Solution:
def maxLength(self, arr: List[str]) -> int:
def max_len_of_merged_word(words):
largest, M = 0, len(words)
for i in range(M):
word_set_1 = set(words[i])
size = len(words[i])
for j in range(M):
if j == i:
continue
word_set_2 = set(words[j])
if word_set_1.isdisjoint(word_set_2):
size += len(words[j])
word_set_1 = word_set_1.union(word_set_2)
largest = max(largest, size)
return largest
strs = [arr[i]
for i in range(len(arr)) if len(arr[i]) == len(set(arr[i]))]
return max(
max_len_of_merged_word(strs),
max_len_of_merged_word(sorted(strs, reverse=True)))
Memory Best
class Solution:
def maxLength(self, arr: List[str]) -> int:
return self.helper('', arr, 0)
def helper(self, curr, arr, idx):
res = len(curr)
if idx >= len(arr):
return res
for i in range(idx, len(arr)):
if not set(curr) & set(arr[i]) and (len(arr[i]) == len(set(arr[i]))):
res = max(res, self.helper(curr + arr[i], arr, i + 1))
return res
/**
* @param {string[]} arr
* @return {number}
*/
var maxLength = function (arr) {
let optSet = new Set();
for (let word of arr) optimize(optSet, word);
optArr = [...optSet];
return dfs(optArr, 0, 0);
};
const optimize = (optSet, word) => {
let charBitSet = 0;
for (let c of word) {
const mask = 1 << (c.charCodeAt() - 97);
if (charBitSet & mask) return;
charBitSet += mask;
}
optSet.add(charBitSet + (word.length << 26));
};
const dfs = (optArr, pos, res) => {
const oldChars = res & ((1 << 26) - 1),
oldLen = res >> 26;
let best = oldLen;
for (let i = pos; i < optArr.length; i++) {
const newChars = optArr[i] & ((1 << 26) - 1),
newLen = optArr[i] >> 26;
if (newChars & oldChars) continue;
const newRes = oldChars + newChars + ((oldLen + newLen) << 26);
best = Math.max(best, dfs(optArr, i + 1, newRes));
}
return best;
};
func maxLength(arr []string) int {
c := []uint32{}
max := 0
for _, s := range arr {
var mask uint32
for _, c := range s {
mask = mask | 1<<(c-'a')
}
if len(s) != bits.OnesCount32(mask) {
continue
}
c = append(c, mask)
}
dfs(c, 0, 0, &max)
return max
}
func dfs(c []uint32, index int, mask uint32, max *int) {
*max = Max(*max, bits.OnesCount32(mask))
for i := index; i < len(c); i++ {
if mask&c[i] == 0 {
dfs(c, i+1, mask|c[i], max)
}
}
return
}
func Max(a, b int) int {
if a > b {
return a
}
return b
}
class Solution {
private func isUnique(_ str: String) -> Bool {
let set = Set<Character>(str)
return set.count == str.count
}
func maxLength(_ arr: [String]) -> Int {
var combos = [String]()
var maximum = 0
combos.append("")
for s in arr {
for c in combos {
let str = c + s
if isUnique(str) {
combos.append(str)
maximum = max(maximum, str.count)
}
}
}
return maximum
}
}
class Solution {
fun getMaxLength(
arr: List<String>,
charsInstring: Array<Int>,
uniqueLength: Int,
i: Int,
maxLengthTillNow: Int
): Int {
if (i >= arr.size) return maxLengthTillNow
var maxLength = 0
if (charsInstring[i] != -1 && charsInstring[i] and uniqueLength == 0) {
var includeLength =
getMaxLength(
arr,
charsInstring,
uniqueLength or charsInstring[i],
i + 1,
maxLengthTillNow + arr[i].length
)
maxLength = includeLength
}
var excludeLength = getMaxLength(arr, charsInstring, uniqueLength, i + 1, maxLengthTillNow)
maxLength = maxOf(maxLength, excludeLength)
return maxLength
}
fun maxLength(arr: List<String>): Int {
val charsInstring: Array<Int> = Array(arr.size) { 0 }
arr.forEachIndexed { index, word ->
var number = 0
var unique = true
word.forEach {
if (number and (1 shl (it - 'a')) != 0) {
unique = false
}
number = number or (1 shl (it - 'a'))
}
if (unique == false) {
charsInstring[index] = -1
} else {
charsInstring[index] = number
}
}
return getMaxLength(arr, charsInstring, 0, 0, 0)
}
}