0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

class Solution {
/*  TLE
    public boolean buddyStrings(String s, String goal) {

        for (int i = 0; i < s.length(); i++) {

            char[] ss = s.toCharArray();

            for (int j = 0; j < s.length(); j++) {

                if (i == j) {
                    continue;
                }

                char si = s.charAt(i);
                char sj = s.charAt(j);

                ss[i] = sj;
                ss[j] = si;
                String newS = new String(ss);
                if(goal.equals(newS)){
                    return true;
                }
                ss = s.toCharArray();
            }
        }

        return false;
    }
*/


    public boolean buddyStrings(String s, String goal) {

        // 長さが違うと、どんなSWAPを行ってもGoalにならないので、Falseを返す
        if (s.length() != goal.length()) {
            return false;
        }

        ArrayList<Integer> saveTwoIndex = new ArrayList<>();
        HashMap<Character, Integer> sCharSaveCount = new HashMap<>();

        for (int i = 0; i < s.length(); i++) {
            char sChar = s.charAt(i);
            char goalChar = goal.charAt(i);

            if (sChar != goalChar) {
                // 違う場所をArrayListに保存する
                saveTwoIndex.add(i);
            }
            sCharSaveCount.put(sChar, sCharSaveCount.getOrDefault(sChar, 0) + 1);
        }

        if (s.equals(goal)) {

            // s    = [ab]
            // goal = [ab]
            // -> NG

            // s    = [aa]
            // goal = [aa]
            // -> OK

            // sとgoalが同じである場合、Sを全体検索し、
            // 1個の文字が一つだったらFalse,
            // 1個の文字が二つ以上あれば、True
            for (char sTemp : s.toCharArray()) {
                if (1 < sCharSaveCount.get(sTemp)) {
                    return true;
                }
            }
            return false;
        }


        // 二つのcharを交換する必要があるので、ArrayListの長さが、2でないと、Falseで終了すること
        if (saveTwoIndex.size() != 2) {
            return false;
        }

        // 各Indexを取得する
        int index0 = saveTwoIndex.get(0);
        int index1 = saveTwoIndex.get(1);

        // indexを交換してみて、同じであれば、True
        // 違う場合、False
        return s.charAt(index0) == goal.charAt(index1) && s.charAt(index1) == goal.charAt(index0);
    }
}

上記の解説を参考しました

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?