码迷,mamicode.com
首页 > 其他好文 > 详细

1510. 亲密字符串(回顾)

时间:2020-04-25 19:41:18      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:header   初始化   testcase   aaa   ase   anim   span   abc   cti   

1510. 亲密字符串

中文English

给定两个由小写字母构成的字符串A 和B,只要我们可以通过交换A中的两个字母得到与B相等的结果,就返回true;否则返回false

样例

Example 1:

Input: A = "ab", B = "ba"
Output: true

Example 2:

Input: A = "ab", B = "ab"
Output: false

Example 3:

Input: A = "aa", B = "aa"
Output: true

Example 4:

Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true

Example 5:

Input: A = "", B = "aa"
Output: false

注意事项

1.0 <= A.length <= 20000
2.0 <= A.length <= 20000
3.A and B consist only of lowercase letters.

 
输入测试数据 (每行一个参数)如何理解测试数据?
class Solution:
    """
    @param A: string A
    @param B: string B
    @return: bool
    """
    ‘‘‘
    大致思路:
    1.首先先判断长度是否相等,如果不相等,直接return Flase。初始化l = [],v =[],dic ={},根据字符计数。flag=Flase,如果当前字符大于1,则flag=True.
    2.然后循环A,如果A[i] != B[i]的话,则写入到l和v里面,如果l长度大于2的话,则reurn Flase。
    3.根据对应的索引在B中和v进行判断,如果相等,则返回True,否则False。
    4.如果是c==1,并且A==B的话,则表示只有一个字符,则返回True,否则False(还有特殊情况aa,aa 和ab,ab考虑。)
    ‘‘‘
    def buddyStrings(self, A, B):
        
        if len(A) != len(B):
            return False
        
        l,v =[],[]
        dic = {}
        flag = False
        for i in range(len(A)):
            ##字符计数,只要有两个相等的即可判断,比如abacd,abacd。
            if A[i] not in dic:
                dic[A[i]] = 1
            else:
                dic[A[i]] += 1
                if dic[A[i]] > 1:
                    flag = True

            if A[i] != B[i]:
                l.append(i)
                v.append(A[i])
                if len(l) > 2:
                    return False
        #aa,aa的情况
        if A == B:
            if flag == True:
                return True
            else:
                return False


        if l != []:
            if B[l[0]] == v[1] and B[l[1]] == v[0]:
                return True
            return  False

 

1510. 亲密字符串(回顾)

标签:header   初始化   testcase   aaa   ase   anim   span   abc   cti   

原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12774298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!