leetcode-161周赛-1247-交换字符使得字符串相同

题目描述:

 

 

 

 自己的提交:

class Solution:
    def minimumSwap(self, s1: str, s2: str) -> int:
        count = {"xy":0,"yx":0}
        for i in range(len(s1)):
            if s1[i] == s2[i]:
                continue
            elif s1[i] == "x" and s2[i] == "y":
                count["xy"] += 1
            elif s1[i] == "y" and s2[i] == "x":
                count["yx"] += 1
        m = count["xy"] % 2
        n = count["yx"] % 2
        if [m,n] in [[1,0],[0,1]]:
            return -1
        else:
            return count["xy"]//2 + count["yx"]//2 + m + n 

优化:

class Solution:
    def minimumSwap(self, s1: str, s2: str) -> int:
        if len(s1) != len(s2): return -1
        xy = yx = 0
        for c1, c2 in zip(s1, s2):
            if c1 == c2: continue
            if c1 == 'x': xy += 1
            else: yx += 1
        if xy&1 != yx&1: return -1
        return ((xy+1)>>1) + ((yx+1)>>1)

 

posted @ 2019-11-04 14:05  oldby  阅读(279)  评论(0编辑  收藏  举报