检查Python字符串的两半是否至少包含一个不同的字符


假设我们有一个小写字符串;我们必须检查是否可以从中间分割字符串,这将得到两个至少在一个字符上不同的部分。它们可能包含不同的字符或每个字符的频率不同。如果字符串长度为奇数,则忽略中间元素并检查其余元素。

因此,如果输入类似于s = "helloohekk",则输出将为True,因为"helloohekk"的左半部分是"hello",右半部分是"ohekk",左右两部分不同。

为了解决这个问题,我们将遵循以下步骤:

  • left_freq := 一个空映射
  • right_freq := 一个空映射
  • n := s的长度
  • 对于范围从0到(n/2)-1的i,执行:
    • left_freq[s[i]] := left_freq[s[i]] + 1
  • 对于范围从(n/2)到n-1的i,执行:
    • right_freq[s[i]] := right_freq[s[i]] + 1
  • 对于s中的每个字符,执行:
    • 如果right_freq[char]与left_freq[char]不同,则:
      • 返回True
  • 返回False

让我们来看下面的实现,以便更好地理解:

示例

 在线演示

from collections import defaultdict
def solve(s):
   left_freq = defaultdict(int)
   right_freq = defaultdict(int)
   n = len(s)
   for i in range(n//2):
      left_freq[s[i]] += 1
   for i in range(n//2, n):
      right_freq[s[i]] += 1
   for char in s:
      if right_freq[char] != left_freq[char]:
         return True
   return False
s = "helloohekk"
print(solve(s))

输入

"helloohekk"

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

True

更新于:2020年12月30日

125 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告