Skip to content

2839. Check if Strings Can be Made Equal With Operations I 👍

  • Time: $O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  bool canBeEqual(string s1, string s2) {
    for (const string& a : swappedStrings(s1))
      for (const string& b : swappedStrings(s2))
        if (a == b)
          return true;
    return false;
  }

 private:
  vector<string> swappedStrings(const string& s) {
    vector<char> chars(s.begin(), s.end());
    return {s, string({chars[2], chars[1], chars[0], chars[3]}),
            string({chars[0], chars[3], chars[2], chars[1]}),
            string({chars[2], chars[3], chars[0], chars[1]})};
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public boolean canBeEqual(String s1, String s2) {
    for (final String a : swappedStrings(s1))
      for (final String b : swappedStrings(s2))
        if (a.equals(b))
          return true;
    return false;
  }

  private List<String> swappedStrings(final String s) {
    List<String> res = new ArrayList<>();
    char[] chars = s.toCharArray();
    res.add(s);
    res.add(new String(new char[] {chars[2], chars[1], chars[0], chars[3]}));
    res.add(new String(new char[] {chars[0], chars[3], chars[2], chars[1]}));
    res.add(new String(new char[] {chars[2], chars[3], chars[0], chars[1]}));
    return res;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def canBeEqual(self, s1: str, s2: str) -> bool:
    def swappedStrings(s: str) -> list[str]:
      chars = list(s)
      return [chars,
              ''.join([chars[2], chars[1], chars[0], chars[3]]),
              ''.join([chars[0], chars[3], chars[2], chars[1]]),
              ''.join([chars[2], chars[3], chars[0], chars[1]])]

    return any(a == b
               for a in swappedStrings(s1)
               for b in swappedStrings(s2))