【问题标题】:Counting the number of sub-strings that are palindrome [duplicate]计算回文子串的数量[重复]
【发布时间】:2015-11-20 18:51:43
【问题描述】:

我今天在hackerearth.com 上解决了一个问题。 https://www.hackerearth.com/problem/algorithm/subpalindrome-4/description/

问题:
对于作为输入给出的每个字符串,您需要告诉我们它的回文子序列的数量(不一定是不同的)。请注意,空字符串不是回文。
样本输入
1
aab
样本输出
4
解释: “aab”的回文子序列是:“a”、“a”、“b”、“aa”,方法返回4。

我必须计算回文的子字符串(不区分)的总数。我必须通过两个测试用例,其中一个成功,并且样本输入也成功运行。第二个测试用例失败,匹配率为 35.29%。

这是我在 Java 中不使用 StringBuffer 类编写的代码:

import java.util.*;

class TestClass {
    int palin(String a)
    {
        int l=a.length();
        for(int i=0;i<l/2;i++)
        {
            if(a.charAt(i)!=a.charAt(l-1-i))
            return -1;
        }

        return 1;

    }
    public static void main(String args[] ) throws Exception {

        TestClass ob=new TestClass();

        Scanner in=new Scanner(System.in);
        int N = in.nextInt();
        in.nextLine(); /*I have included this because I have seen that when I
        input the string, the number is the value of N appears at its start*/
        for (int ii = 0; ii < N; ii++)
        {
            String aa=in.nextLine();
            String a=aa.toLowerCase();
            int l=a.length();
            int n=l;
            for(int i=0;i<l;i++)
            {
                for(int j=i+2;j<=l;j++)
                {
                    if(ob.palin(a.substring(i,j))>0)
                    n++;
                }
            }
            System.out.println(n);
        }
    } 

我在逻辑上是不是在某个地方出错了?还是我错过了什么?

【问题讨论】:

    标签: java algorithm palindrome


    【解决方案1】:

    字符串的子序列不同于子字符串。例如,考虑字符串“ABC”:

    子字符串:“”、“A”、“B”、“C”、“AB”、“BC”、“ABC”

    子序列:所有子字符串,加上“AC”

    关于子序列的更多信息:https://en.wikipedia.org/wiki/Subsequence

    【讨论】:

    • 好地方,欢迎来到 Stack Overflow :)
    猜你喜欢
    • 2015-01-05
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 2020-05-30
    相关资源
    最近更新 更多