leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

count-number-of-texts.dart (1650B)


      1 //Given an input count the number of possible texts sent by pressing the keys of a phone keyboard in this order.
      2 //The problem is looking for all permutations of strings that can result from pressing the number keys in a certain order.
      3 //My code does not work for very large inputs because it recurses too deep so I will convert this to iterative and resubmit.
      4 
      5 class Solution {
      6     Map<int , List<String>> options = {};
      7     Map<String , int> memo = {};
      8     Solution(){
      9     options = {
     10         2 : ["a" , "b" , "c"],
     11         3 : ["d" , "e" , "f"],
     12         4 : ["g" , "h" , "i"],
     13         5 : ["j" , "k" , "l"],
     14         6 : ["m" , "n" , "o"],
     15         7 : ["p" , "q" , "r" , "s"],
     16         8 : ["t" , "u" , "v"],
     17         9 : ["w" , "x" , "y" , "z"]
     18     };
     19   }
     20   int countTexts(String pressedKeys) {
     21       if(pressedKeys.length == 0){
     22           return 1;
     23       }
     24       String current_str = pressedKeys;
     25       if(memo[current_str] != null){
     26           return (memo[current_str] ?? 0);
     27       }
     28       int ret_val = 0;
     29       String new_pressed = pressedKeys.substring(1);
     30       ret_val += countTexts(new_pressed);
     31       ret_val = (ret_val % (pow(10, 9) + 7)).toInt();
     32       String current = pressedKeys.substring(0,1);
     33       for(int i = 1 ; i < (options[int.parse(current)]?.length ?? 0) && i < pressedKeys.length; ++i){
     34           if(pressedKeys[i] != pressedKeys[i - 1]){
     35               break;
     36           }
     37           new_pressed = new_pressed.substring(1);
     38           ret_val += countTexts(new_pressed);
     39           ret_val = (ret_val % (pow(10, 9) + 7)).toInt();
     40       }
     41       memo[current_str] = ret_val;
     42       return (ret_val % (pow(10, 9) + 7)).toInt();
     43   }
     44 }