回文子串

时间:2016-03-07 07:12:21

标签: python string algorithm palindrome

给定两个字符串 A B ,每个字符串由小写字母组成, 是否有可能选择一些非空字符串s1和s2,其中s1是A的子字符串,s2是B的子字符串,这样s1 + s2是一个回文字符串。这里'+'表示字符串之间的串联。

例如:

Case 1:

A='abc'
B='abc'

解决方案选择s1& s的一种可能方式s2是s1 =“ab”,s2 =“a”使得s1 + s2,即“aba”是回文。

Case 2:
A='a'
B='b'

解决方案:没有办法选择s1& s2使得s1 + s2是回文。

注意: 如果可能,请打印“是”否则打印“否” 找到两个字符串之间的回文子串的算法是什么?

3 个答案:

答案 0 :(得分:2)

两个字符串有一个共同的字母是必要的(并且足够)。

def test(a, b):
    return not set(a).isdisjoint(set(b))

答案 1 :(得分:0)

此程序可为您发布的问题提供相当好的结果。

#palindromic substrings in Python
s1='potter'
s2='topper'
count=0
print('substring  substring    allowed \n of s1 \t   of s2\tpalindromes')
for m in range(len(s1)):
   for n in range(m+1,len(s1)+1):   # n > m
    subs1=s1[m:n]               # substring of s1
    l = n-m                     # length of subs1
    print (subs1,'.................................')
    for r in range(len(s2)-l+1):
        subs2=s2[r:r+l]
        print('\t',subs2)
        if subs1==subs2[::-1]:  # string reversal
            print ('\t\t\t',subs1+subs2)
            count=count+1
if count==0:
    print ('No')
else:
    print('Yes')

我在这里基本上做的是获取s1的子串。子串的长度逐渐增加,如'p','po','pot','pott','potte','potter'。并且对应于s1的每个子字符串,我们检查来自另一个字符串s2的相等长度的子字符串。输出的一部分如下所示:

substring  substring    allowed 
 of s1      of s2      palindromes
p .................................
            t
            o
            p
                         pp
            p
                         pp
            e
            r
po .................................
           to
           op
                        poop
           pp
           pe
           er
pot .................................
           top
                        pottop
           opp
           ppe
           per
 :          :              :
 :          :              :

例如,对应于s1中的'pot',我们在s2中得到'top','opp','ppe','per',其长度与'pot'相同。但只有'顶部'反转才能回到'底池'。因此,当'pot'与'top'连接时,它会形成一个回文。类似地,可以从这两个词中获得的其他回文是'pp','poop','pottop','oo','otto','tt','ee'和'rr'。   但是我的程序没有解决制作奇数字母的回文问题。

答案 2 :(得分:0)

您需要记住一件事:从字符串开始:单词对也具有单字符单词;

说明:

  1. 计算单词数计算功能:通过两个循环语句
  2. 回文检查功能

现在登录就像

public static int getCountOfPalindromAvailable (String orignalValue){
  int count=0;
  for (int parent=0; parent< orignalValue.length(); parent++ ){
     for (int child=parent; child <orignalValue.length(); child++){ 
          System.out.println(orignalValue.substring(parent, child+1) +" 
      orignalValue");
          if (isPalindrom(orignalValue.substring(parent, child+1))){
             System.out.println(orignalValue.substring(parent, child+1)+" 
           isPalindrom");
             count+=1;
           }
      }
  }
  return count;
}

public static boolean isPalindrom (String orignalValue){
   return orignalValue.equals(new StringBuilder(orignalValue).reverse().toString());
}
相关问题