LeetCode Solutions

893. Groups of Special-Equivalent Strings

Time:

Space:

			

class Solution {
 public:
  int numSpecialEquivGroups(vector<string>& A) {
    unordered_set<string> set;

    for (const string& s : A) {
      string even;
      string odd;
      for (int i = 0; i < s.length(); ++i)
        if (i % 2 == 0)
          even += s[i];
        else
          odd += s[i];
      sort(begin(even), end(even));
      sort(begin(odd), end(odd));
      set.insert(even + odd);
    }

    return set.size();
  }
};
			

class Solution {
  public int numSpecialEquivGroups(String[] A) {
    Set<String> set = new HashSet<>();

    for (final String s : A) {
      String even = "";
      String odd = "";
      for (int i = 0; i < s.length(); ++i)
        if (i % 2 == 0)
          even += s.charAt(i);
        else
          odd += s.charAt(i);
      char[] evenCharArray = even.toCharArray();
      char[] oddCharArray = odd.toCharArray();
      Arrays.sort(evenCharArray);
      Arrays.sort(oddCharArray);
      set.add(new String(evenCharArray) + new String(oddCharArray));
    }

    return set.size();
  }
}
			

class Solution:
  def numSpecialEquivGroups(self, A: List[str]) -> int:
    return len({''.join(sorted(s[::2])) + ''.join(sorted(s[1::2])) for s in A})