Hard 在字符串S中查找T中的字符串 @CareerCup
2013-12-13 11:58
357 查看
后缀树!!
Ref:
http://blog.csdn.net/v_july_v/article/details/6897097
http://blog.csdn.net/at8008/article/details/17256321
package Hard; import java.util.ArrayList; import java.util.HashMap; /** * Given a string s and an array of smaller strings T, design a method to search s for each small string in T. 译文: 给一个字符串S和一个字符串数组T(T中的字符串要比S短许多),设计一个算法, 在字符串S中查找T中的字符串。 * */ public class S18_8 { // 后缀树节点 static class SuffixTreeNode { HashMap<Character, SuffixTreeNode> children = new HashMap<Character, SuffixTreeNode>(); char value; ArrayList<Integer> indexes = new ArrayList<Integer>(); public SuffixTreeNode() { } public void insertString(String s, int index) { indexes.add(index); if (s != null && s.length() > 0) { value = s.charAt(0); SuffixTreeNode child = null; if (children.containsKey(value)) { child = children.get(value); } else { child = new SuffixTreeNode(); children.put(value, child); } String remainder = s.substring(1); child.insertString(remainder, index); } } public ArrayList<Integer> search(String s) { if (s == null || s.length() == 0) { return indexes; } else { char first = s.charAt(0); if (children.containsKey(first)) { String remainder = s.substring(1); return children.get(first).search(remainder); } } return null; } } // 后缀树 static class SuffixTree { SuffixTreeNode root = new SuffixTreeNode(); public SuffixTree(String s) { for (int i = 0; i < s.length(); i++) { String suffix = s.substring(i); root.insertString(suffix, i); } } public ArrayList<Integer> search(String s) { return root.search(s); } } public static void main(String[] args) { String testString = "mississippi"; String[] stringList = { "is", "sip", "hi", "sis" }; SuffixTree tree = new SuffixTree(testString); for (String s : stringList) { ArrayList<Integer> list = tree.search(s); if (list != null) { System.out.println(s + ": " + list.toString()); } } } }
Ref:
http://blog.csdn.net/v_july_v/article/details/6897097
http://blog.csdn.net/at8008/article/details/17256321
相关文章推荐
- Hard 动态查找中位数 @CareerCup
- Arrays_Strings 压缩字符串 @CareerCup
- Recursion 字符串的全排列 String Permutation @CareerCup
- Sorting_Searching 有序矩阵中查找数 @CareerCup
- Sorting&Searching 二分法找有空字符串的数组 @CareerCup
- Hard 不用+号实现两个数之和 @CareerCup
- Hard 随机洗牌函数 @CareerCup
- Hard 计算0到n之间2的个数 @CareerCup
- Hard 随机选择subset @CareerCup
- Hard 随机选择subset @CareerCup
- Hard 计算0到n之间2的个数 @CareerCup
- Hard 随机洗牌函数 @CareerCup
- Hard 大文本找两个单词最短距离 @CareerCup
- Hard 不用+号实现两个数之和 @CareerCup
- CareerCup之1.8 字符串移位包含问题
- Arrays_Strings 判断字符串中的字符是否唯一@CareerCup
- Arrays_Strings 翻转字符串 @CareerCup
- careercup top 150判断字符串中字符是否唯一(字符不重复)
- CareerCup之1.2C风格字符串翻转
- Arrays_Strings 判断两个字符串是否有相同的字符 @CareerCup