Beat 99% answer, using just String array


  • 0
    I
    		char[] c = pattern.toCharArray();
    		String[] arr = str.split(" ");
    		if (c.length != arr.length)
    			return false;
    		String[] strs = new String[26];
    		for (int i = 0; i < c.length; i++) {
    			int pos = c[i] - 97;
    			if (strs[pos] == null) {
    				for (int j = 0; j < i; j++) {
    					if (arr[j].equals(arr[i]))
    						return false;
    				}
    				strs[pos] = arr[i];
    			}
    			else if (strs[pos] != null && !strs[pos].equals(arr[i]))
    				return false;
    		}
    		return true;
    	}

  • 0
    A

    @IIN said in Beat 99% answer, using just String array:

    		if (strs[pos] == null) {
    			for (int j = 0; j < i; j++) {
    				if (arr[j].equals(arr[i]))
    					return false;
    

    Unfortunately, this is linear search with worst case O(n^2) time complexity. It invalidates the purpose of hashmap. We use hashmap because we want to get O(1) search time.


Log in to reply
 

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