Advertisement
rishu110067

Untitled

Feb 3rd, 2022
688
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.90 KB | None | 0 0
  1.    
  2.     public static List<string> get_words_from_phone_number(string phone_number) {
  3.         // Write your code here.
  4.         var phoneRef = new List<List<char>>(){
  5.             new List<char>(){' '},
  6.             new List<char>(){'a','b','c'},
  7.             new List<char>(){'d','e','f'},
  8.             new List<char>(){'g','h','i'},
  9.             new List<char>(){'j','k','l'},
  10.             new List<char>(){'m','n','o'},
  11.             new List<char>(){'p','q','r','s'},
  12.             new List<char>(){'t','u','v'},
  13.             new List<char>(){'w','x','y','z'}
  14.         };
  15.         var results = new List<string>();
  16.         var slate = new List<char>();
  17.         Helper(phone_number.Length,phoneRef,0,slate,results,phone_number);
  18.        
  19.         // result can be empty for strings having only 0 and 1
  20.         if(results.Count == 0){
  21.             results.Add("-1");
  22.         }
  23.         return results;
  24.     }
  25.    
  26.     public static void Helper(int k, List<List<char>> phoneRef, int currentVal, List<char> slate, List<string> results, string phone_number){
  27.         if(k == 0){
  28.             // Don't append slate to result if slate is empty
  29.             if(slate.Count != 0){
  30.                 results.Add(new string(slate.ToArray()).Trim());
  31.             }
  32.             return;
  33.         }
  34.         if(k < 0){
  35.             return;
  36.         }
  37.        
  38.         // if the number at currentVal is 0 or 1, then don't add anything to slate and move ahead
  39.         if(phone_number[currentVal] == '0' || phone_number[currentVal] == '1'){
  40.             Helper(k-1, phoneRef, currentVal+1, slate, results, phone_number);  
  41.             return;
  42.         }
  43.        
  44.         int i = phone_number[currentVal] - '1';
  45.         for(int j = 0; j < phoneRef[i].Count;j++){
  46.             slate.Add(phoneRef[i][j]);
  47.             Helper(k-1, phoneRef, currentVal+1, slate, results, phone_number);
  48.             slate.RemoveAt(slate.Count-1);
  49.         }
  50.     }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement