Skip to main content

Daily Leetcode – 1807

00:01:13:33

It's been over a year since my last leetcode post. Not sure how valuable this is with the rate of AI progress.

So basically you are given a string, s and an array of string pairs knowledge.

The string s looks something like (name)is(age)yearsold and all you need to do is replace the words within the brackets with the the second string in the array of pairs. So the first string acts as a key, and the second acts as the value - seems like a familiar data structure...

So my solution was just to reformat knowledge from a vector<vector<string>> to a unordered_map<string,string> for O(1) look-up time.

Then we just create an empty result string, iterate through s and append any characters. However, if we reach an open bracket, we convert the word inside to a string and query it with the hasmap. If it exists, we replace the whole (...) blob with the string value from the hashmap, otherwise, we replace it with ?.

cpp
class Solution {
public:
    string evaluate(string s, vector<vector<string>>& knowledge) {
        unordered_map<string,string> umap;

        for(vector<string>& pair : knowledge) {
            umap[pair[0]] = pair[1];
        }

        string result = "";

        for(int i = 0; i < s.size(); i++) {
            if(s[i] == '(') {
                i++;
                string key = "";
                while(s[i] != ')') {
                    key.push_back(s[i]);
                    i++;
                }
                if(umap.contains(key)) {
                    string replacement = umap[key];
                    result.append(replacement);
                } else {
                    result.push_back('?');
                }
            } else {
                result.push_back(s[i]);
            }
        }
        return result;
    }
};