变量名拆分 -头条2019笔试题

输入要使用sc.next(), 如果使用sc.nextLine().split(" ") 将会超时!!!

import java.util.*;
public class Main {
    static long[] p, h;
    static long get(int l, int r) {
        /*求字符串的第l个字符到第r个字符(s[l-1,..r-1])的hash*/    
        return h[r] - h[l-1]*p[r-l+1];
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        int n = str.length(), P = 131;
        p = new long[n+1];
        h = new long[n+1];
        p[0] = 1;
        char[] s = str.toCharArray();
        for(int i=1; i <= n; i++) {
            h[i] = h[i-1] * P + s[i-1];
            p[i] = p[i-1] * P;
        }
        Set<Long> set = new HashSet<>();
        while(sc.hasNext()) {
            char[] ss = sc.next().toCharArray();
            long t = 0L;
            for(int j=0; j < ss.length; j++) {
                t = t*P + ss[j];
            }
            set.add(t);
        }
        boolean[] f = new boolean[n+1];
        f[0] = true;
        for(int i=1; i <= n; i++) {
            for(int j=i; j > 0; j--) {
                if(set.contains(get(j, i)) && f[j-1] == true) {
                    f[i] = true; break;
                }
            }
        }
        if(f[n])
            System.out.println("True");
        else
            System.out.println("False");
    }
}

原文地址:https://www.cnblogs.com/lixyuan/p/13036841.html