Leetcode 1002. 查詢共用字元
阿新 • • 發佈:2022-05-20
給你一個字串陣列 words ,請你找出所有在 words 的每個字串中都出現的共用字元( 包括重複字元),並以陣列形式返回。你可以按 任意順序 返回答案。
示例 1:
輸入:words = ["bella","label","roller"]
輸出:["e","l","l"]
示例 2:
輸入:words = ["cool","lock","cook"]
輸出:["c","o"]
提示:
- 1 <= words.length <= 100
- 1 <= words[i].length <= 100
- words[i] 由小寫英文字母組成
主要思路:
先以長度排序
之後一個字元一個字元遍歷
Code:
class Solution { public: vector<string> commonChars(vector<string>& words) { vector<string>res; sort(words.begin(),words.end()); for(int i=0;i<words[0].length();i++) { string sub=words[0].substr(i,1); bool flag=false; vector<int>vec; for(int j=1;j<words.size();j++) { string temp=words[j]; int pos=temp.find(sub); if(pos==string::npos) { vec.clear(); flag=true; break; } vec.push_back(pos); } if(!flag) { for(int j=1;j<words.size();j++) { words[j].erase(vec[j-1],1); } res.push_back(sub); } } return res; } };