题解 | #统计回文#

统计回文

https://www.nowcoder.com/practice/9d1559511b3849deaa71b576fa7009dc

import java.util.Scanner;

//思路: (1)找到合适位置进行插入
//    (2)判断字符串是不是回文串
public class Main {
    // 方法一:写个方法判断字符串是否为回文串
    /**
    
    public static boolean isLegal(StringBuilder str) {
        for (int i = 0, j = str.length() - 1; i < j;
                i++, j--) {
            if (str.charAt(i) != str.charAt(j)) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        while (in.hasNextLine()) {
            StringBuilder A = new StringBuilder(in.nextLine());
            StringBuilder B = new StringBuilder(in.nextLine());
            int count = 0;
            for (int i = 0; i <= A.length(); i++) {
                StringBuilder tmp = new StringBuilder(A);
                tmp.insert(i, B);
                if(isLegal(tmp)){
                    count++;
                }
            }
            System.out.println(count);
        }
    }
     */
    //方法二:将字符串翻转,看翻转后的字符串是不是和翻转前相同,
    //相同为回文串
    public static void main(String[] args) {
        Scanner in = new Scanner (System.in);
        while (in.hasNext()) {
            StringBuffer A = new StringBuffer(in.nextLine());
            StringBuffer B = new StringBuffer(in.nextLine());
            int count = 0;
            for (int i = 0; i <= A.length(); i++) {
                //复制A,因为每次插入都会破坏字符串
                StringBuffer tmp = new StringBuffer(A); 
                tmp.insert(i,B);
                //准备字符串ret ,用来存放字符串翻转后的结果。
                StringBuffer ret = new StringBuffer(tmp);
                ret.reverse();
                if (ret.toString().equals(tmp.toString())) {
                    count++;
                }
            }
            System.out.println(count);
        }
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 12:05
点赞 评论 收藏
分享
06-10 21:15
门头沟学院 Java
宁阿:好多这种没🧠的公司,他们估计都不知道毕业的人不能给安排实习岗
实习吐槽大会
点赞 评论 收藏
分享
07-09 12:12
门头沟学院 Java
5月底投简历7月初开奖收获秋招第一个offer,虽然白菜价,但至少能保底了
土木转行ing:土木博士想转图像,最后拿了 tp 提前批 sp 最低档,感觉性价比不高
TP-LINK开奖132人在聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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