您的位置:首页 > 其它

Hard 在字符串S中查找T中的字符串 @CareerCup

2013-12-13 11:58 357 查看
后缀树!!

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: