Prefix and Suffix Search

ㅋㅋ·2022년 6월 18일
0

알고리즘-leetcode

목록 보기
14/135

단어 사전을 만드는데 접두사와 접미사로 검색할 수 있도록 해야 한다.

class WordFilter {
public:
    unordered_map<string, int> dictionary{};
    
    WordFilter(vector<string>& words) {
        
        int index{0};
        for (auto &word : words)
        {
            int wordSize = min((int)word.size(), 10);
            for (int i = 1; i <= wordSize; i++)
            {
                string prefix = word.substr(0, i);
                
                for (int j = 0; j < wordSize; j++)
                {
                    string suffix = word.substr(j, wordSize - j);
                    
                    string sum{prefix + '@' + suffix};
                    
                    dictionary[sum] = index;
                }
                
            }
            
            index++;
        }
    }
    
    int f(string prefix, string suffix) {
        
        string key{prefix + '@' + suffix};
        if (dictionary.count(key) == 0)
        {
            return -1;
        }
        
        return dictionary[key];
    }
};

/**
 * Your WordFilter object will be instantiated and called as such:
 * WordFilter* obj = new WordFilter(words);
 * int param_1 = obj->f(prefix,suffix);
 */

0개의 댓글