天天看點

Leetcode 1002. 查找共用字元

Leetcode 1002. 查找共用字元

給你一個字元串數組 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] 由小寫英文字母組成
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;
    }
};