string - 如何查找并检查给定字符串中是否存在任何子字符串及其反向?

标签 string algorithm

示例

假设给定的字符串是'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/

相关文章:

java - 在 Java 中,如何检查字符串是否包含子字符串(忽略大小写)?

c++ - '\0' 相关问题

Java 和数组 - 按升序插入排序

algorithm - 这是一个正确的算法,如果它是连接的,它会接受图 G 吗?

arrays - 谁长得快?登录或登录! ?以及如何获得 T(n)

javascript - Content Aware Sidbars 插件博客页面上的错误通知

python - 如何在Python中查找字符串列表中所有出现的字符串并返回int列表?

javascript - JS/NodeJS JSON 缓冲区到字符串

java - 用递归算法打包一组盒子

输入的算法复杂度是固定大小的