/**
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
*/
/**
Thinking:
Ransom <-> Magazine 以下簡稱為 R M
這個題目的意思是 R 可以由 M 構(gòu)造丝格,而且都是小寫字母盛杰,這樣 M 和 R 里面出現(xiàn)
的同一個字母 M 的次數(shù)要比 R 多才滿足。
于是這個問題就轉(zhuǎn)換了堆排序的基礎(chǔ),給定 26 個小寫字母的堆澎剥,然后統(tǒng)計 M 里面
字母出現(xiàn)的次數(shù)励堡,然后 R 去匹配艇炎,一旦 M 中的某一個堆的數(shù)目小于 R 中的耸成,則不
滿足了。
*/
func canConstruct(_ ransom: String, from magazine: String) -> Bool {
guard ransom.lengthOfBytes(using: .ascii) > 0,
magazine.lengthOfBytes(using: .ascii) > 0
else {
return false
}
var lowerCaseArray:[Int] = [Int].init(repeating: 0, count: 26)
//注意Swift中的value的獲取
let aValue = ("a" as UnicodeScalar).value
for ch in magazine.unicodeScalars {
lowerCaseArray[Int(ch.value - aValue)] += 1
}
for ch in ransom.unicodeScalars {
let chValue = Int(ch.value - aValue)
lowerCaseArray[chValue] -= 1
//小于零則是無法由當(dāng)前數(shù)目構(gòu)造
if (lowerCaseArray[chValue] < 0) {
return false
}
}
return true
}
canConstruct("ab", from: "abc")
canConstruct("", from: "c")
canConstruct("aa", from: "aba")
canConstruct("abc", from: "ab")
383. Ransom Note
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門炊汤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來正驻,“玉大人弊攘,你說我怎么就攤上這事」檬铮” “怎么了襟交?”我有些...
- 文/不壞的土叔 我叫張陵,是天一觀的道長伤靠。 經(jīng)常有香客問我捣域,道長锤悄,這世上最難降的妖魔是什么酝惧? 我笑而不...
- 正文 為了忘掉前任,我火速辦了婚禮粘捎,結(jié)果婚禮上形纺,老公的妹妹穿的比我還像新娘丘侠。我一直安慰自己,他們只是感情好逐样,可當(dāng)我...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著打肝,像睡著了一般脂新。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上粗梭,一...
- 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼醉锅!你這毒婦竟也來了兔簇?” 一聲冷哼從身側(cè)響起,我...
- 正文 年R本政府宣布恩伺,位于F島的核電站赴背,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏晶渠。R本人自食惡果不足惜凰荚,卻給世界環(huán)境...
- 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望褒脯。 院中可真熱鬧便瑟,春花似錦、人聲如沸番川。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽颁督。三九已至践啄,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間沉御,已是汗流浹背屿讽。 一陣腳步聲響...
推薦閱讀更多精彩內(nèi)容
- Given an arbitrary ransom note string and another string ...
- 題目 Given an arbitrary ransom note string and another stri...
- Q: Given an arbitrary ransom note string and another stri...