统计回文_WY18_java

统计回文

http://www.nowcoder.com/questionTerminal/9d1559511b3849deaa71b576fa7009dc

解题思路:
1.遍历字符串A中的所有可以插入的位置(A.length也需要算入)
2.使用StringBuilder进行拼接
3.使用双指针法进行判断是否回文(即i,j指针分别指向0和 length-1,然后遍历判断两个字符是否相等)
这种判断方法的时间复杂度只需要reverse之后进行比较的一半,所以比较推荐
代码:

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            StringBuilder s1 = new StringBuilder(sc.nextLine());
            StringBuilder s2 = new StringBuilder(sc.nextLine());
            int count = 0;
            for(int i= 0;i<=s1.length();i++){
                StringBuilder temp = new StringBuilder(s1);
                temp.insert(i,s2);
                if(isLegal(temp)){
                    count++;
                }
            }
            System.out.println(count);
        }
    }
    public static  boolean isLegal(StringBuilder temp){
        int i = 0;
        int j = temp.length()-1;
        while(i<j){
            if(temp.charAt(i++)!=temp.charAt(j--)){
                return false;
            }
        }
        return true;
    }
全部评论

相关推荐

2025-12-15 11:27
门头沟学院 Java
哇哇的菜鸡oc:所有人不要理会,就好了,后面他就知道怎么回事了,只能说有的时候市场都是被宰的人搞坏的
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务