Java 30ms O(n) Solution ,program exits as early as possible


  • 0
    4
     public boolean canConstruct(String ransomNote, String magazine) {
    		if (ransomNote == null || ransomNote.equals("")) {
    			return true;
    		}
    		if (magazine == null || magazine.equals("")) {
    			return false;
    		}
    		int[] nums1 = new int[26];
    		List<Character> cur = new ArrayList<Character>();
    		for (int i = 0; i < ransomNote.length(); i++) {
    			nums1[ransomNote.charAt(i) - 'a']++;
    			if (!cur.contains(ransomNote.charAt(i))) {
    				cur.add(ransomNote.charAt(i));
    			}
    		}
    		for (int i = 0; i < magazine.length(); i++) {
    			if (cur.contains(magazine.charAt(i))) {
    				nums1[magazine.charAt(i)-'a']--;
    				if (nums1[magazine.charAt(i)-'a']==0) {
    					cur.remove((Character)magazine.charAt(i));
    				}
    				if (cur.size()==0) {
    					return true;
    				}
    			}
    			
    		}
    		return false;
    	}
    

Log in to reply
 

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