LeetCode1247. 交換字符使得字符串相同

1247. Minimum Swaps to Make Strings Equal

[Medium] You are given two strings s1 and s2 of equal length consisting of letters "x" and "y" only. Your task is to make these two strings equal to each other. You can swap any two characters that belong to different strings, which means: swap s1[i] and s2[j].

Return the minimum number of swaps required to make s1 and s2 equal, or return -1 if it is impossible to do so.

Example 1:

Input: s1 = "xx", s2 = "yy"
Output: 1
Explanation:
Swap s1[0] and s2[1], s1 = "yx", s2 = "yx".

Example 2:

Input: s1 = "xy", s2 = "yx"
Output: 2
Explanation:
Swap s1[0] and s2[0], s1 = "yy", s2 = "xx".
Swap s1[0] and s2[1], s1 = "xy", s2 = "xy".
Note that you can't swap s1[0] and s1[1] to make s1 equal to "yx", cause we can only swap chars in different strings.

Example 3:

Input: s1 = "xx", s2 = "xy"
Output: -1

Example 4:

Input: s1 = "xxyyxyxyxx", s2 = "xyyxyxxxyx"
Output: 4

Constraints:

  • 1 <= s1.length, s2.length <= 1000
  • s1, s2 only contain 'x' or 'y'.

題目:有兩個長度相同的字符串 s1s2,且它們其中 只含有 字符 "x""y",你需要通過「交換字符」的方式使這兩個字符串相同。每次「交換字符」的時候,你都可以在兩個字符串中各選一個字符進行交換。

交換隻能發生在兩個不同的字符串之間,絕對不能發生在同一個字符串內部。也就是說,我們可以交換 s1[i]s2[j],但不能交換 s1[i]s1[j]

最後,請你返回使 s1s2 相同的最小交換次數,如果沒有方法能夠使得這兩個字符串相同,則返回 -1

思路:貪心。共分爲三種情況:

  • s1[i]=s2[i]的情況無需交換;
  • xxyy的情況只需交換一次;
  • xyyx則需交換兩次。

工程代碼下載 GitHub

class Solution {
public:
    int minimumSwap(string s1, string s2) {
        int n = s1.size();

        int xy = 0, yx = 0;
        for(int i = 0; i < n; ++i){
            if(s1[i] == 'x' && s2[i] == 'y')
                xy += 1;
            else if(s1[i] == 'y' && s2[i] == 'x')
                yx += 1;
        }

        int res = 0;
        res += xy / 2;
        res += yx / 2;

        if(xy % 2 != yx % 2)
            return -1;

        return res += (xy % 2) * 2;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章