Minimum Length Substrings

	public static int minLengthSubstring(String s, String t) {
		int min = Integer.MAX_VALUE;
		boolean found = false;
		for (int i = 0; i <= s.length(); i++) {
			for (int j = i; j <= s.length(); j++) {
				String takedString = s.substring(i, j);
				boolean contained = true;
				HashMap<Character, Integer> h = new HashMap<Character, Integer>();
				for (Character c : t.toCharArray()) {
					h.put(c, h.getOrDefault(c, 0) + 1);
				}
				for (Character c : takedString.toCharArray()) {
					h.put(c, h.getOrDefault(c, 0) - 1);
				}

				for (Character c : h.keySet()) {
					if (h.get(c) > 0)
						contained = false;
				}
				if (contained) {
					found = true;
					min = Integer.min(min, takedString.length());
				}
			}
		}
		if (!found)
			return -1;
		return min;
	}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s