【贪心】B024_交换字符使得字符串相同(统计类型个数)

一、题目描述

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

二、题解

方法一:统计类型个数

  • 相同位置具有相同字符,则不需要交换。
  • 相同位置具有不同字符,则需要交换,
    • 对于 x y \cfrac{x}{y} x y \cfrac{x}{y} 或者 y x \cfrac{y}{x} y x \cfrac{y}{x} 这样的一对,则需要交换 1 次即可。
    • 对于 x y \cfrac{x}{y} y x \cfrac{y}{x} 这样的一对,则需要交换两次。
public int minimumSwap(String S1, String S2) {
    int xy = 0, yx = 0;
    for (int i = 0; i < S1.length(); i++) {
        if (S1.charAt(i) == 'x' && S2.charAt(i) == 'y') {
            xy++;
        } else if (S1.charAt(i) == 'y' && S2.charAt(i) == 'x') {
            yx++;
        }
    }
    int step = xy/2 + yx/2;
    xy %= 2; yx %= 2;
    if (xy + yx == 1) return -1;
    if (xy + yx == 2) step += 2;
    return step;
}

复杂度分析

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( 1 ) O(1)
发布了691 篇原创文章 · 获赞 151 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/105413524