|
|
恭喜lz啊,下周面求人品~
根据lz的提示把第二题写了一下,有问题欢迎指出
另外第三题不是很懂啊,lz说按照逗号和双引号隔开,但是逗号的部分也没有隔开啊看结果的话。而且双引号可以嵌套吗?求问lz都有什么样的corner case啊。。非常感谢- public class LongestSubDomain {
- private class TrieNode {
- String str;
- Map<String, TrieNode> map;
- boolean isLeaf;
- public TrieNode(String str) {
- this.str = str;
- this.map = new HashMap<>();
- this.isLeaf = false;
- }
- }
- TrieNode root = new TrieNode("#");
- public static void main(String[] args) {
- LongestSubDomain lsd = new LongestSubDomain();
- String[] domains = {".com", ".cn", ".service.com", ".net", ".youku.net"};
- String url = "yeah.hello.youku.net";
- for (String str : domains) {
- lsd.insert(str);
- }
- String res = lsd.startWith(url);
- System.out.println(res);
- }
- public void insert(String domain) {
- String[] temp = domain.split("\\.");
- TrieNode node = root;
- for (int i = temp.length - 1; i >= 0; i--) {
- if (temp[i].length() == 0) continue;
- if (node.map.containsKey(temp[i])) {
- node = node.map.get(temp[i]);
- } else {
- TrieNode newNode = new TrieNode(temp[i]);
- node.map.put(temp[i], newNode);
- node = newNode;
- }
- }
- node.isLeaf = true;
- }
- public String startWith(String url) {
- String[] temp = url.split("\\.");
- TrieNode node = root;
- String res = "";
- int index = temp.length - 1;
- for (int i = temp.length - 1; i >= 0; i--) {
- if (temp[i].length() == 0) continue;
- if (node.map.containsKey(temp[i])) {
- res = "." + temp[i] + res;
- node = node.map.get(temp[i]);
- } else {
- if (!node.isLeaf) {
- res = "";
- } else {
- index = i;
- }
- break;
- }
- }
- return temp[index] + res;
- }
- }
复制代码 |
|