字符串、字典匹配算法
来源:互联网 发布:诚信网络一条龙 编辑:程序博客网 时间:2024/05/22 10:49
package StringAndArray;import java.util.HashSet;import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * 一字符串s与一个包含多个字符串的set字典dict,查询set字典中部分字符串是否能拼接成s * * @author fh * */public class Word_Break { public static void main(String[] args) { Set<String> dict = null; String s=null; s="programcreek"; dict = new HashSet<String>(); dict.add("programcree"); dict.add("program"); dict.add("creek"); boolean b=wordBreak(s, dict); System.out.println(s+"在字典dict是否可查询:"+b); // Regrex(); } /** * The key to solve this problem by using dynamic programming approach: * * Define an array t[] such that t[i]==true => 0-(i-1) can be segmented * using dictionary Initial state t[0] == true * * Time: O(string length * dict size) * * One tricky part of this solution is the case: * * INPUT: "programcreek", ["programcree","program","creek"]. */ public static boolean wordBreak(String s, Set<String> dict) { boolean[] t = new boolean[s.length() + 1]; t[0] = true;// 需要一个初始值 for (int i = 0; i < s.length(); i++) { if (!t[i])// 该字符与前面拼接的字符串在dict中不存在,则跳出本次循环 continue; // 循环遍历字典,查出以i为起点的所有匹配子字符串 for (String sub : dict) { int len = sub.length(); int end = i + len; //剩余待匹配字符串长度小于字典中的匹配子字符串 if (end > s.length()) continue; if(s.substring(i, end).equals(sub)){ t[end]=true; if(end==s.length()){ return true; } } } } return false; } // 正则法解题 private static void Regrex() { HashSet<String> dict = new HashSet<String>(); dict.add("go"); dict.add("goal"); dict.add("goals"); dict.add("special"); StringBuilder sb = new StringBuilder(); for (String s : dict) { sb.append(s + "|"); } String pattern = sb.toString().substring(0, sb.length() - 1); pattern = "(" + pattern + ")*"; System.err.println(pattern); Pattern p = Pattern.compile(pattern); Matcher m = p.matcher("goalgoalspecial"); if (m.matches()) { System.out.println("match"); } }}
0 0
- 字符串、字典匹配算法
- Google字符串模糊匹配算法,字典树模糊查询
- Google字符串模糊匹配算法,字典树模糊查询
- Google字符串模糊匹配算法,字典树模糊查询
- 字符串匹配算法之二------Trie字典树
- 算法 字符串匹配算法
- 字符串匹配的三个算法(KMP+字典树+AC自动机)
- 字符串匹配算法
- BM字符串匹配算法
- KMP 字符串匹配算法
- 字符串匹配算法
- 字符串匹配算法
- 字符串匹配算法(摘)
- 字符串匹配算法
- 字符串匹配算法
- 字符串匹配的算法
- kmp字符串匹配算法
- 字符串匹配算法
- android的handler looper msg
- python运行类,能够执行
- java >>>
- 链表反转
- UILabel的相关属性设置
- 字符串、字典匹配算法
- c#字符串转json对象(一)
- 自定义 URL Scheme 完全指南
- 如何使能RT5350 1T2R ANTENNA DIVERSITY
- IIS中给网站添加匿名访问用户图文教程
- caffe+ubuntu14.04+install
- 框架 的分页
- 在报表中给session赋值实现报表间参数共享
- 用链表实现二叉树