题解 | #统计回文#

统计回文

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);
        }
    }
}

全部评论

相关推荐

暮雨轻歌:看起来hr不能接受我菜查看图片
点赞 评论 收藏
分享
许愿ssp的咸鱼很不想泡池子:import python as pyhton
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务