educative.io

Can i use HashSet here instead of HashMap

Can i use HashSet here instead of HashMap

public static int findLength_IsThisCorrect(String str, int k) {
char[] cArr = str.toCharArray();
int len = cArr.length;
int subStrLen = Integer.MIN_VALUE;
int windowStart = 0;

	 for(int windowEnd=0;windowEnd<len;windowEnd++) {
		 
		 String subStr = str.substring(windowStart, windowEnd);
		 
		 int charLen = getDistinctCharLen(subStr);
		 if ( charLen == k ) {				 
			 subStrLen = Math.max( subStrLen, subStr.length() );
		 }else if ( charLen > k ) {
			 windowStart++;
		 }
	 }
	 return subStrLen;
 }

 public static int getDistinctCharLen(String s) {
	 char[] arr = s.toCharArray();
	 Set<Character> set = new HashSet<Character>();
	 for(int i=0;i<arr.length;i++) {
		 set.add(arr[i]);
	 }
	 return set.size();
 }

Hi @Paresh_Patnaik

Yes, you can use HashSet here but HashMap is relatively faster than HashSet as it uses the hashing technique whereas HashSet uses HashMap object.

Shaheryaar Kamal | Technical Content Engineer