4 line Java Solution using List


  • 0
    S

    4 line Java Solution using List. But, definitely not as efficient as https://discuss.leetcode.com/topic/53864/java-o-n-solution-easy-to-understand.

    public static boolean canConstructzz(String ransomNote, String magazine) {
        	List<Character> list = new ArrayList<Character>();    	
        	for(int i = 0; i < ransomNote.length(); i++) list.add(ransomNote.charAt(i));
        	for(int i = 0; i < magazine.length(); i++) if(list.contains(magazine.charAt(i))) list.remove((Character)magazine.charAt(i));
            return list.isEmpty();
        }

  • 0
    E

    @shamanthnorway This is a clever idea, but using a set would be better than a list, since we get constant time lookup.


  • 0
    E

    @shamanthnorway ...soooo, here's literally your exact code, just using set instead. Oddly, it fails for two test cases... I need to look into why.

          HashSet<Character> list = new HashSet<Character>();    	
        	for(int i = 0; i < ransomNote.length(); i++) list.add(ransomNote.charAt(i));
        	for(int i = 0; i < magazine.length(); i++) if(list.contains(magazine.charAt(i))) list.remove((Character)magazine.charAt(i));
            return list.isEmpty();
        }

Log in to reply
 

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