[LeetCode] Check if Strings Can be Made Equal With Operations I

아르당·2026년 11월 11일

LeetCode

목록 보기
589/626
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

문자열 길이가 4인 두 개의 문자열 s1과 s2가 주어지고, 영어 소문자로 구성된다.
두 문자열 중 어느 하나에 대해 다음 연산을 원하는 만큼 여러 번 적용할 수 있다.

  • j - i를 만족하는 두 인덱스 i와 j를 선택하고, 문자열에서 해당 인덱스에 위치한 두 문자를 바꿔라.

문자열 s1과 s2를 같게 만들 수 있다면 true, 그렇지 않다면 false를 반환해라.

Example

#1
Input: s1 = "abcd", s2 = "cdab"
Output: true

#2
Input: s1 = "abcd", s2 = "dacd"
Output: false

Constraints

  • s1.length == s2.length == 4
  • s1과 s2는 오직 영어 소문자로 구성된다.

Solved

class Solution {
    public boolean canBeEqual(String s1, String s2) {
        char[] even1 = new char[]{s1.charAt(0), s1.charAt(2)};
        char[] even2 = new char[]{s2.charAt(0), s2.charAt(2)};
        char[] odd1 = new char[]{s1.charAt(1), s1.charAt(3)};
        char[] odd2 = new char[]{s2.charAt(1), s2.charAt(3)};

        Arrays.sort(even1);
        Arrays.sort(even2);
        Arrays.sort(odd1);
        Arrays.sort(odd2);

        return Arrays.equals(even1, even2) && Arrays.equals(odd1, odd2);
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글