My C++ code (2 ms), append a new char to strings in the vector for each new digit


  • 0
    D
    // assume all the digits are in [2, 9]
    class Solution {
    public:
        vector<string> letterCombinations(string digits) {
            vector<string> res;
            vector<string> map = {"", "", "abc", "def","ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            int sSize = digits.size();
            int i, j, k, vSize, mSize;
            
            if(sSize>0)
            {
                res.push_back("");
                for(i=0; i<sSize; i++)
                {
                    vSize = res.size();
                    mSize = map[ digits[i] - '0' ].size();
                    
                    for(j =1; j<mSize; j++ ) // note j starts from 1, since the vector already have the  strings that will be appended with the first char of the string corresponding to the current digit.
                    {
                        for(k =0; k<vSize; k++ )
                        {
                            res.push_back(res[k] + map[ digits[i] -'0'][j]); // append a new char to the strings in the vector and add to the vector
                        }
                    }
                    for(k =0; k<vSize; k++ )
                    {
                        res[k] += map[ digits[i] -'0'][0];
                    }
                }
            }
            return res;
        
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.