Re: [閒聊] 每日LeetCode已回收

看板Marginalman作者 (四葉天下第一)時間3年前 (2022/11/03 18:33), 編輯推噓1(100)
留言1則, 1人參與, 3年前最新討論串84/719 (看更多)
※ 引述《Rushia (みけねこ的鼻屎)》之銘言: : 2131. Longest Palindrome by Concatenating Two Letter Words : 給予很多個長度為2的字串,求出將這些字串任意拼接後可得的最長迴文長度。 : Exaple: : Input: words = ["lc","cl","gg"] : Output: 6 : Explanation: One longest palindrome is "lc" + "gg" + "cl" = "lcggcl", of : length 6. : Note that "clgglc" is another longest palindrome that can be created. 一開始想法是用雙重迴圈去跑後面有沒有可以回文的字串 前面答案都對但是遇到太大量的資料 會 Time Limit Exceeded 所以後來改用map來存取每個字串出現的次數 ones用來存連續字母 twos用來存不同字母的 然後twos的部分 使用map<string, pair<int, int>> 的形式 前面string先sort過 然後再用迴圈回去算就好 大約是O(n)吧 ------ C++ 程式碼: class Solution { public: int longestPalindrome(vector<string>& words) { map<string, pair<int, int>> twos; map<string, int> ones; for (auto word : words) { if (word[0] == word[1]) { ones[word]++; } else { string s = word; sort(s.begin(), s.end()); if (s == word) { twos[s].first++; } else { twos[s].second++; } } } int res = 0; for (auto& two : twos) { res += min(two.second.first, two.second.second) * 4; } for (auto& one : ones) { res +=( one.second / 2) * 4; } for (auto& one : ones) { if ((one.second % 2) == 1) { res += 2; break; } } return res; } }; -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.229.103.22 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1667471602.A.A61.html

11/03 19:39, 3年前 , 1F
大師
11/03 19:39, 1F
文章代碼(AID): #1ZOvZofX (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ZOvZofX (Marginalman)