Easy to understand C++


  • 0
    class Solution {
    public:
        vector<string> letterCombinations(string digits) {
            
            vector<string> combos;
            
            unordered_map<char, string> map;
            map['2'] = "abc";
            map['3'] = "def";
            map['4'] = "ghi";
            map['5'] = "jkl";
            map['6'] = "mno";
            map['7'] = "pqrs";
            map['8'] = "tuv";
            map['9'] = "wxyz";
            
            for ( char digit : digits ){
                
                if (map.find(digit) == map.end()) { continue; } // digits w/o letters such as 0 or 1
                
                if (combos.empty()){ // first digit, append digit's letters onto the vector of combos
                    
                    for ( char letter : map[digit] ){
                        
                        combos.push_back( string(1, letter) );
                                         
                    }
                 } else { // create a new vector by appending subsequent digit's letters
                          // onto the old vector of combos
                     
                     vector<string> new_combos;
                     for (int i=0; i < combos.size(); i++){
                         for ( char letter : map[digit] ){
                             new_combos.push_back(combos[i] + string(1, letter) );
                         }
                     }
                     combos = new_combos;
                 }
             }
            
            return combos;
         }
     };
    

Log in to reply
 

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