Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.
Example:
Input: s = "abba"
Output: 4
Approach
Java
import java.util.Vector;public class SherlockAnagram {public static void main(String[] args) {String s = "abba";System.out.println(sherlockAndAnagrams(s));}static boolean checkAnagrams(String s, String t) {int ch1[] = new int[26];int ch2[] = new int[26];for (int i = 0; i < s.length(); i++) {ch1[s.charAt(i) - 'a']++;}for (int i = 0; i < t.length(); i++)ch2[t.charAt(i) - 'a']++;for (int i = 0; i < 26; i++) {if (ch1[i] - ch2[i] != 0)return false;}return true;}static int sherlockAndAnagrams(String s) {int count = 0;for (int i = 1; i <= s.length(); i++) {Vector<String> str = new Vector<>();for (int j = 0; j + i <= s.length(); j++) {str.add(s.substring(j, j + i));}for (int p = 0; p < str.size(); p++) {for (int q = p + 1; q < str.size(); q++) {if (checkAnagrams(str.get(p), str.get(q)))count++;}}}return count;}}
C++
#include <bits/stdc++.h>using namespace std;bool checkAnagrams(string s, string t){int ch1[26] = {0};int ch2[26] = {0};for (int i = 0; i < s.size(); i++){ch1[s[i] - 'a']++;}for (int i = 0; i < t.size(); i++)ch2[t[i] - 'a']++;for (int i = 0; i < 26; i++){if (ch1[i] - ch2[i] != 0)return false;}return true;}int sherlockAndAnagrams(string s){int count = 0;for (int i = 1; i <= s.length(); i++){vector<string> str;for (int j = 0; j + i <= s.length(); j++){str.push_back(s.substr(j, i));}for (int p = 0; p < str.size(); p++){for (int q = p + 1; q < str.size(); q++){if (checkAnagrams(str[p], str[q]))count++;}}}return count;}int main(){string s = "abba";cout << sherlockAndAnagrams(s) << "\n";return 0;}
No comments:
Post a Comment