Get the App
SLTechnology News&Howtos  ›  Development  › 

How to understand the intimate string of LeetCode in Python

Shulou Source: shulou.com Published: 2022-06-02 23:54:41 10月04日 Update

This article will explain in detail how to understand the intimate string of LeetCode in Python. The content of the article is of high quality, so Xiaobian shares it with you as a reference. I hope you have a certain understanding of relevant knowledge after reading this article.

Title: Given two strings of lowercase letters A and B, returns true if we can get the same result as B by swapping the two letters in A; otherwise returns false. Input: A = "ab", B = "ba" Output: trueFrom: LeetCode analysis

1. When A is not equal to B:

I. Length must be consistent

II. Component elements remain consistent

III. The difference between the two must be 2(ab, ba)

Here, use regular expressions to query whether the elements in the same position in B are the same as A one by one, and return a list composed of True and False. False means that the elements in the same position are inconsistent, that is, there is a difference value. Here, as long as the number of False is 2, it can be guaranteed.

2. When A equals B:

I. is not empty

II. At least 2 (aa, aba, abab) duplicate delay elements within a string

Here, after A is deduplicated, query the number of times the element appears in the initial string, and return a list composed of times, as long as the maximum value of the list element is greater than or equal to 2.

Code:

#!/ usr/bin/env python# -*- coding: utf-8-*-''@ author: maya@software: Pycharm@file: intimateStrings.py @time: 2019/7/24 8:31@desc:'''Title: Given two strings of lowercase letters A and B, returns true as long as we can swap the two letters in A to get the same result as B; otherwise returns false. Input: A = "ab", B = "ba" Output: trueFrom: LeetCode'''import reclass Solution(object): def buddyStrings(self, A, B): """ :type A: str :type B: str :rtype: bool """ equal_result = [True if re.search(data, B[A.index(data)]) else False for data in A] num_result = [len(re.findall(data, A)) for data in list(set(A))] return True if (A != B and (len(A) == len(B)) and (set(A) == set(B) and equal_result.count(False) == 2)) \ or (A == B != "" and max(num_result) >= 2) else False About how to understand the intimate string of LeetCode in Python is shared here, I hope the above content can be of some help to everyone, you can learn more knowledge. If you think the article is good, you can share it so that more people can see it.

Tags: Characters strings elements two letters same consistent intimate location content can be passed lowercase differences quantity articles more times knowledge articles results Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Shulou Tech Info macOS MariaDB Huawei