?LeetCode刷題實(shí)戰(zhàn)411:最短獨(dú)占單詞縮寫(xiě)

示例
示例1:
"apple", ["blade"] -> "a4"?(因?yàn)?"5"?或者 "4e"?同時(shí)也是 "blade"?的縮寫(xiě)形式,所以它們是無(wú)效的縮寫(xiě))
示例2:
"apple", ["plain", "amber", "blade"] -> "1p3"?(其他有效的縮寫(xiě)形式還包括 "ap3", "a3e", "2p2", "3le", "3l1")。
解題
class?Solution?{
public:
????string?minAbbreviation(string?target, vector<string>& dictionary)?{
????????if?(dictionary.empty()) return?to_string((int)target.size());
????????priority_queueint, string>, vector int, string>>, greater int, string>>> q;
????????q = generate(target);
????????while?(!q.empty()) {
????????????auto?t = q.top(); q.pop();
????????????bool?no_conflict = true;
????????????for?(string?word : dictionary) {
????????????????if?(valid(word, t.second)) {
????????????????????no_conflict = false;
????????????????????break;
????????????????}
????????????}
????????????if?(no_conflict) return?t.second;
????????}
????????return?"";
????}
????priority_queueint, string>, vector int, string>>, greater int, string>>> generate(string?target) {
????????priority_queueint, string>, vector int, string>>, greater int, string>>> res;
????????for?(int?i = 0; i < pow(2, target.size()); ++i) {
????????????string?out = "";
????????????int?cnt = 0, size = 0;
????????????for?(int?j = 0; j < target.size(); ++j) {
????????????????if?((i >> j) & 1) ++cnt;
????????????????else?{
????????????????????if?(cnt != 0) {
????????????????????????out += to_string(cnt);
????????????????????????cnt = 0;
????????????????????????++size;
????????????????????}
????????????????????out += target[j];
????????????????????++size;
????????????????}
????????????}
????????????if?(cnt > 0) {
????????????????out += to_string(cnt);
????????????????++size;
????????????}
????????????res.push({size, out});
????????}
????????return?res;
????}
????bool?valid(string?word, string?abbr)?{
????????int?m = word.size(), n = abbr.size(), p = 0, cnt = 0;
????????for?(int?i = 0; i < abbr.size(); ++i) {
????????????if?(abbr[i] >= '0'?&& abbr[i] <= '9') {
????????????????if?(cnt == 0?&& abbr[i] == '0') return?false;
????????????????cnt = 10?* cnt + abbr[i] - '0';
????????????} else?{
????????????????p += cnt;
????????????????if?(p >= m || word[p++] != abbr[i]) return?false;
????????????????cnt = 0;
????????????}
????????}
????????return?p + cnt == m;
????}
};
LeetCode1-400題匯總,希望對(duì)你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)401:二進(jìn)制手表
LeetCode刷題實(shí)戰(zhàn)402:移掉 K 位數(shù)字
LeetCode刷題實(shí)戰(zhàn)403:青蛙過(guò)河
LeetCode刷題實(shí)戰(zhàn)404:左葉子之和
LeetCode刷題實(shí)戰(zhàn)405:數(shù)字轉(zhuǎn)換為十六進(jìn)制數(shù)
LeetCode刷題實(shí)戰(zhàn)406:根據(jù)身高重建隊(duì)列
LeetCode刷題實(shí)戰(zhàn)407:接雨水 II
LeetCode刷題實(shí)戰(zhàn)408:有效單詞縮寫(xiě)
LeetCode刷題實(shí)戰(zhàn)409:最長(zhǎng)回文串
LeetCode刷題實(shí)戰(zhàn)410:分割數(shù)組的最大值
