判断字符串对称

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/flower_CSDN/article/details/82563028

第四范式的笔试题,也不是很难,非想装个逼,优化下执行效率,本来想用String的用了StringBuilder,唉,结果智障的,一直append,没发现问题所在,应该重新赋值啊!重新new啊!唉,mdzz,最后还是用我的String吧,都差不多,生气,又不咋难,本来可以AC的。唉,第四范式再见!

package dsfs;

import java.util.Scanner;

//a1223a
//22
public class Main2 {

    public static String duicheng(String input) {
        String sb = "";
        if (!(input.equals("") || input.length() == 0)) {
            if (input.length() == 1) {
                return input;
            } else {
                String sb2 = "";
                char[] chs = input.toCharArray();
                for (int i = 1; i < chs.length; i++) {

                    // 奇对称
                    sb2 = "";
                    for (int j = 1; (i - j >= 0) && (i + j <= chs.length - 1); j++) {

                        if (chs[i - j] == chs[i + j]) {
                            if (j == 1) {
                                sb2 = chs[i] + "";
                            }
                            sb2 = chs[i - j] + sb2.toString() + chs[i + j];
                            if (sb2.length() > sb.length()) {
                                sb = sb2;
                            }
                            if (sb.toString().length() >= chs.length) {
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                    if (sb.length() >= chs.length) {
                        break;
                    }

                }
                // 偶对称
                if (sb.length() < 3) {

                    for (int i = 0; i < chs.length; i++) {
                        sb2 = "";
                        for (int j = 0; (i - j >= 0) && (i + j + 1 <= chs.length - 1); j++) {
                            if (chs[i - j] == chs[i + j + 1]) {
                                sb2 = chs[i - j] + sb2.toString() + chs[i + j + 1];
                                if (sb2.length() > sb.length()) {
                                    sb = sb2;
                                }
                            } else {
                                break;
                            }
                            if (sb.length() >= chs.length) {
                                break;
                            }
                        }

                        if (sb.length() >= chs.length) {
                            break;
                        }
                    }
                }
            }
        }
        return sb;
    }

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

        System.out.println(duicheng(input));
    }

}

猜你喜欢

转载自blog.csdn.net/flower_CSDN/article/details/82563028