Python3程序最小化要更改的字符以使字符串的左右旋转相同
给定一个由小写英文字母组成的字符串S ,任务是找到要更改的最小字符数,以使字符串的左右旋转相同。
例子:
Input: S = “abcd”
Output: 2
Explanation:
String after the left shift: “bcda”
String after the right shift: “dabc”
Changing the character at position 3 to ‘a’ and character at position 4 to ‘b’, the string is modified to “abab”.
Therefore, both the left and right rotations becomes “baba”.
Input: S = “gfg”
Output: 1
Explanation:
After updating the character at position 1 to ‘g’, the string becomes “ggg”.
Therefore, the left and right rotation are equal.
方法:解决问题的关键观察是当字符串的长度是偶数时,那么偶数索引处的所有字符和奇数索引处的字符必须相同,左右旋转相同。对于奇数长度的字符串,所有字符必须相等。请按照以下步骤解决问题:
- 检查字符串的长度是否为偶数,则要更改的最小字符数是字符串的长度,不包括偶数索引和奇数索引处出现次数最多的元素的频率。
- 否则,如果字符串的长度是奇数,则要更改的最小字符数是字符串的长度,不包括字符串中出现频率最高的字符。
- 打印获得的最终计数。
下面是上述方法的实现:
Python3
# Python3 Program of the
# above approach
# Function to find the minimum
# characters to be removed from
# the string
def getMinimumRemoval(str):
n = len(str)
# Initialize answer by N
ans = n
# If length is even
if(n % 2 == 0):
# Frequency array for odd
# and even indices
freqEven = {}
freqOdd = {}
for ch in range(ord('a'),
ord('z') + 1):
freqEven[chr(ch)] = 0
freqOdd[chr(ch)] = 0
# Store the frequency of the
# characters at even and odd
# indices
for i in range(n):
if(i % 2 == 0):
if str[i] in freqEven:
freqEven[str[i]] += 1
else:
if str[i] in freqOdd:
freqOdd[str[i]] += 1
# Stores the most occurring
# frequency for even and
# odd indices
evenMax = 0
oddMax = 0
for ch in range(ord('a'),
ord('z') + 1):
evenMax = max(evenMax,
freqEven[chr(ch)])
oddMax = max(oddMax,
freqOdd[chr(ch)])
# Update the answer
ans = ans - evenMax - oddMax
# If length is odd
else:
# Stores the frequency of the
# characters of the string
freq = {}
for ch in range('a','z'):
freq[chr(ch)] = 0
for i in range(n):
if str[i] in freq:
freq[str[i]] += 1
# Stores the most occurring
# characterin the string
strMax = 0
for ch in range('a','z'):
strMax = max(strMax,
freq[chr(ch)])
# Update the answer
ans = ans - strMax
return ans
# Driver Code
str = "geeksgeeks"
print(getMinimumRemoval(str))
# This code is contributed by avanitrachhadiya2155
6
时间复杂度: O(N)
辅助空间: O(1)
请参阅完整文章最小化要更改的字符以使字符串的左右旋转相同以获取更多详细信息!