Java 2ms cartesian product


  • 0
    B
    public class Solution {
    public List<String> combine(String keys, List<String> list)
    {
    	List<String> result = new ArrayList<>();
    
    	for (char c : keys.toCharArray())
    	{
    		StringBuilder sb = new StringBuilder();
    		sb.append(c);
    		if (list.size() > 0)
    		{
    			for (String s : list)
    			{
    				sb = new StringBuilder();
    				sb.append(s);
    				sb.append(c);
    				result.add(sb.toString());
    			}
    		}
    		else
    		{
    			result.add(sb.toString());	
    		}
    	}
    
    	return result;
    }
    
    public List<String> letterCombinations(String digits) {
        List<String> solution = new ArrayList<>();
    	Map<Character, String> keyPad = new HashMap<>();
    	keyPad.put('2', "abc");
    	keyPad.put('3', "def");
    	keyPad.put('4', "ghi");
    	keyPad.put('5', "jkl");
    	keyPad.put('6', "mno");
    	keyPad.put('7', "pqrs");
    	keyPad.put('8', "tuv");
    	keyPad.put('9', "wxyz");
    
    	int i = 0;
    	while (i < digits.length())
    	{
    	    if (digits.charAt(i) == '1' || digits.charAt(i) == '0')
    		{
    			return new ArrayList<>();
    		}
    		solution = combine(keyPad.get(digits.charAt(i)), solution);
    		i++;
    	}
    
    	return solution; 
    }
    }

Log in to reply
 

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