-->

Almost equivalent Strings - HackerRank Java Solution

Almost equivalent Strings - HackerRank

Two strings are considered “almost equivalent” if they have the same length AND for each lowercase letter x, the number of occurrences of x in the two strings differs by no more than 3. There are two string arrays, s and i, that each contains n strings. Strings s[i] and t[i] are the i pair of strings. They are of equal length and consist of lowercase English letters. For each pair of strings, determine if they are almost equivalent.


SOLUTION : JAVA

	public List areAlmostEquivalent(List s, List t) {
		List results = new ArrayList<>();
		for (int i = 0; i < s.size(); i++) {
			int[] count_s = new int[27];
			int[] count_t = new int[27];

			for (int charIdx = 0; charIdx < s.get(i).length(); charIdx++) {
				count_s[s.get(i).charAt(charIdx) - 'a']++;
			}
			for (int charIdx = 0; charIdx < t.get(i).length(); charIdx++) {
				count_t[t.get(i).charAt(charIdx) - 'a']++;
			}
			int k = 0;
			for (; k < 26; k++) {
				if (Math.abs(count_s[k] - count_t[k]) > 3) break;
			}
			results.add(k == 26 ? "YES" : "NO");
		}
		return results;
	}


VERDICT: ALL TEST CASES PASSED 


Post a Comment

0 Comments