<style> html, body, .ui-content { background: #222222; color: #00BFFF; } /* 設定 code 模板 */ .markdown-body code, .markdown-body tt { background-color: #ffffff36; } .markdown-body .highlight pre, .markdown-body pre { color: #ddd; background-color: #00000036; } .hljs-tag { color: #ddd; } .token.operator { background-color: transparent; } /* 設定連結 */ a, .open-files-container li.selected a { color: #89FFF8; } a:hover, .open-files-container li.selected a:hover { color: #89FFF890; } </style> ###### tags: `Leetcode` # 2306. Naming a Company ###### Link : https://leetcode.com/problems/naming-a-company/description/ ## 題目 1. 從ideas中選擇2個不同的名字,稱它們為ideaA和ideaB。 2. 將ideaA和ideaB的第一個字母互換。 3. 如果這兩個新名字都不在原來的ideas中,那麼ideaA ideaB(ideaA和ideaB的連接,用空格隔開)就是一個有效的公司名稱。 ## 程式碼I ```cpp= class Solution { public: long long distinctNames(vector<string>& ideas) { unordered_set<string> dic[26]; for(auto &str : ideas){ //按照開頭放入除了開頭以外的字串 dic[str[0] - 'a'].insert(str.substr(1)); } long long ans = 0; //計算答案 for(int i = 0;i < 25;++i){ for(int j = i + 1;j < 26;++j){ int repeat = 0;//兩個set中重複的字串 for(auto &it : dic[j]){//找出有多少重複 if(dic[i].count(it)){ ++repeat; } } //答案為 += 2 * (setA大小 - repeat) * (setB大小 - repeat) ans += 2 * (dic[i].size() - repeat) * (dic[j].size() - repeat); } } return ans; } }; ``` ## Date ### 2023/2/9
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up