prefix(2)
来源:互联网 发布:discuz 标签 seo 编辑:程序博客网 时间:2024/06/10 19:04
/*ID: daniel.20LANG: JAVATASK: prefix */import java.io.*;import java.util.*;public class prefix { static ArrayList<String> prims = new ArrayList<String>(); static char target[] = new char[200002]; static int table[]; public static void initial() throws Exception { BufferedReader f = new BufferedReader(new FileReader("prefix.in")); while (true) { String tmp = f.readLine(); if (tmp.equals(".")) { break; } StringTokenizer st = new StringTokenizer(tmp); while (st.hasMoreTokens()) { prims.add(st.nextToken()); } } String tmp = ""; int start = 0; while((tmp=f.readLine())!=null){ for(int i=0;i<tmp.length();++i) target[start+i]=tmp.charAt(i); start+=tmp.length(); } table = new int[target.length + 1]; Arrays.fill(table, 99999); table[0] = 0; } public static boolean matchString(int t, String tmp) { if (tmp.length() > t) { return false; } for (int j = tmp.length() - 1; j >= 0; --j) { if (tmp.charAt(j) != target[t - tmp.length() + j]) { return false; } } return true; } public static void dp() throws Exception { PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("prefix.out"))); for (int i = 1; i < table.length; ++i) { for (int j = 0; j < prims.size(); ++j) { String tmp = prims.get(j); if (matchString(i, tmp)) { if (table[i - tmp.length()] == 0) { table[i] = 0; break; } } } } for (int i = table.length - 1; i >= 0; --i) { if (table[i] == 0) { out.println(i); out.close(); break; } } } public static void main(String[] args) throws Exception { long t1 = System.currentTimeMillis(); initial(); dp(); System.out.println(System.currentTimeMillis() - t1); System.exit(0); }}
总算找到了为什么读入那么慢,图省事,用了 s+=f.readLine();
不是很确定,估计要查下API,估计String有默认的空间,不停加入超过额定空间,估计需要重新分配内存,这就很耗时间了,以前A题不知道是数据量小,还是没这么简单的用string就能保存,不记得了,没遇到过这个情况。
改过之后算法很快就出来了,对于最大的test case反而只要0.2s......至少哥的算法是efficent的
Test 1: TEST OK [0.162 secs, 30048 KB]
Test 2: TEST OK [0.144 secs, 30048 KB]
Test 3: TEST OK [0.396 secs, 30048 KB]
Test 4: TEST OK [0.450 secs, 30048 KB]
Test 5: TEST OK [0.666 secs, 30048 KB]
Test 6: TEST OK [0.234 secs, 30048 KB]
- prefix(2)
- prefix
- leetcode Longest Common Prefix 2.6 难度系数2
- A:Simple prefix compression来自百炼2
- leetcode -- Longest Common Prefix -- 简单O(n^2)就行
- Codeforces Round #278 (Div. 2) E. Prefix Product Sequence
- [LeetCode-Algorithms-14] "Longest Common Prefix" (2017.10.2-WEEK5)
- lock prefix
- USACO prefix
- USACO/prefix
- make prefix
- Longest Prefix
- Longest Prefix
- unbound prefix
- Prefix tree
- USACO/prefix
- taglib prefix
- Prefix Notation
- 指数哥伦布编码
- 关于CAVLC相关码表在JM程序实现的理解
- 返回上一页的javascript代码
- cavlc编码level的原理和过程
- CAVLC编码过程详解——Sunrise
- prefix(2)
- Eclipse 快捷键
- CAVLC中的前缀和后缀——264小生
- Hanio (for my memory of Grade One)
- 那年,三支玫瑰的花语是我们每人一支
- Java 单态设计模式
- 导入导出Android手机文件
- 自定义标题栏
- SVN服务器配置