示例
假设给定的字符串是'abccbaad'
然后,子字符串将是 'abc',它的反向将是 'cba'
两者都存在于给定的字符串中。
如何找到它们?
如果可能,请提供代码片段。
注意:子串长度 > 1
更新:一个位置的子字符串中使用的字符不应在反向字符串中再次使用。
例如。 假设在子字符串中使用索引 2 中的“c”,那么它不应再用于反向字符串中,但允许使用索引 3 中的“c”。
最佳答案
我假设您想要找到所有其反向也出现在给定字符串中的子字符串。
在那种情况下,建立在这个答案之上 - find all substrings :
def get_all_substrings(input_string):
output_strings = list()
length = len(input_string)
for i in xrange(length): # Iterate through all indices of the string
for j in xrange(i + 1, length): # Iterate through indices starting from i + 1 to end of the string, so as to obtain substrings of length > 1
substr = input_string[i:j + 1] # Slice the substring
if substr[::-1] in input_string: # Check if the substring's reverse exists in the original string
output_strings.append(substr) # If it does, add it to a list
return output_strings
print get_all_substrings("abccbaad") # Output - ['ab', 'abc', 'abcc', 'abccb', 'abccba', 'bc', 'bcc', 'bccb', 'bccba', 'cc', 'ccb', 'ccba', 'cb', 'cba', 'ba', 'aa']
关于string - 如何查找并检查给定字符串中是否存在任何子字符串及其反向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47245934/