题解 | #密码截取#动态规划,三条路径

密码截取

https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.stream.*;
import java.util.regex.*;
import java.util.function.*;


// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        /**
        三种情况 两边加,后面追加,自身
         */
        String line = in.nextLine();
        MirrorString[] d = new MirrorString[line.length() + 1];
        // init
        d[0] = new MirrorString("", true);

        int max = 0;
        for (int i = 1; i < d.length; i++) {
            int currIndex = i - 1;
            int lastIndex = currIndex - 1;
            int mirrorIndex = currIndex - d[i - 1].getLength() - 1;
            char curr = line.charAt(i - 1);

            if (mirrorIndex >= 0 && curr == line.charAt(mirrorIndex)) {
                d[i] = d[i - 1].appendTwo(curr);
            } else if (d[i - 1].canAppendOne(curr)) {
                d[i] = d[i - 1].appendOne(curr);
            } else {
                d[i] = new MirrorString(String.valueOf(curr), true);
            }
            max = Math.max(max, d[i].getLength());
        }
        // System.out.println(
        //     Arrays.stream(d)
        //     .map(m->m.getMirror())
        //     .collect(Collectors.joining(" ")));
        System.out.println(max);
    }
}

class MirrorString {
    private String mirror;
    private boolean isAllSame;

    public MirrorString(String s, boolean same) {
        this.mirror = new String(s);
        this.isAllSame = same;
    }

    boolean canAppendOne(char c) {
        return this.isAllSame && (this.mirror.length() == 0 ||
                                  this.mirror.charAt(0) == c );
    }

    MirrorString appendOne(char c) {
        if (this.mirror.length() == 0) {
            return new MirrorString(String.valueOf(c), true);
        }

        if (this.isAllSame && this.mirror.charAt(0) == c) {
            return new MirrorString(this.mirror + c, true);
        } else {
            return new MirrorString(this.mirror + c, false);
        }
    }

    MirrorString appendTwo(char c) {
        if (this.isAllSame && this.mirror.charAt(0) == c) {
            return new MirrorString(c + this.mirror + c, true);
        } else {
            return new MirrorString(c + this.mirror + c, false);
        }
    }

    boolean isAllSame() {
        return this.isAllSame;
    }

    String getMirror() {
        return this.mirror.toString();
    }

    int getLength() {
        return this.mirror.length();
    }

    boolean isOdd() {
        return this.mirror.length() % 2 != 0;
    }



}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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