Shortest Completing Word

Given a string licensePlate and an array of strings words, find the shortest completing word in words.

completing word is a word that contains all the letters in licensePlateIgnore numbers and spaces in licensePlate, and treat letters as case insensitive. If a letter appears more than once in licensePlate, then it must appear in the word the same number of times or more.

For example, if licensePlate = "aBc 12c", then it contains letters 'a''b' (ignoring case), and 'c' twice. Possible completing words are "abccdef""caaacab", and "cbca".

Return the shortest completing word in words. It is guaranteed an answer exists. If there are multiple shortest completing words, return the first one that occurs in words.

Example:

Input: licensePlate = "1s3 PSt", words = ["step","steps","stripe","stepple"]
Output: "steps"
Explanation: licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step" contains 't' and 'p', but only contains 1 's'.
"steps" contains 't', 'p', and both 's' characters.
"stripe" is missing an 's'.
"stepple" is missing an 's'.
Since "steps" is the only word containing all the letters, that is the answer.

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

string shortestCompletingWord(string licensePlate,
                              vector<string&words)
{
    string res = "";
    int mp[26] = {0};
    for (int i = 0i < licensePlate.size(); i++)
    {
        if (licensePlate[i] >= 'a' && licensePlate[i] <= 'z')
        {
            mp[licensePlate[i] - 'a']++;
        }
        else if (licensePlate[i] >= 'A' && licensePlate[i] <= 'Z')
        {
            mp[licensePlate[i] + 32 - 'a']++;
        }
    }
    int len = INT_MAX;
    for (int i = 0i < words.size(); i++)
    {
        int mp1[26] = {0};
        int flag = 0;

        for (int j = 0j < words[i].size(); j++)
        {
            mp1[words[i][j] - 'a']++;
        }

        for (int j = 0j < 26j++)
        {
            if (mp1[j] < mp[j])
            {
                flag = 1;
                break;
            }
        }

        if (flag == 0)
        {
            if (len > words[i].size())
            {
                len = words[i].size();
                res = words[i];
            }
        }
    }
    return res;
}

int main()
{
    string licensePlate = "1s3 PSt";
    vector<stringwords = {"step""steps""stripe""stepple"};

    cout << shortestCompletingWord(licensePlatewords);

    return 0;
}


No comments:

Post a Comment