字符串

  • 实现一个字符集,只包含 a~z 这 26 个英文字母的 Trie 树
import java.util.LinkedList;
class Node{
	char content;
	boolean isEnd;
	int count;
	LinkedList<Node> childList;
	public Node(char c) {
		childList=new LinkedList<Node>();
		isEnd=false;
		content=c;
		count=0;
	}
	public Node subNode(char c) {
		if(childList!=null) {
			for(Node eachChild:childList) {
				if(eachChild.content==c) {
					return eachChild;
				}
			}
		}
		return null;
	}
}
public class Trie {
	private Node root;
	public Trie() {
		root=new Node(' ');
	}
	public void insert(String word) {
		if(search(word)==true) return;
		Node current=root;
		for(int i=0;i<word.length();i++) {
			Node child=current.subNode(word.charAt(i));
			if(child!=null) {
				current=child;
			}else {
				current.childList.add(new Node(word.charAt(i)));
				current=current.subNode(word.charAt(i));
			}
			current.count++;
		}
		current.isEnd=true;
	}
	public boolean search(String word) {
		Node current=root;
		for(int i=0;i<word.length();i++) {
			if(current.subNode(word.charAt(i))==null)
				return false;
			else
				current=current.subNode(word.charAt(i));
		}
	    if(current.isEnd==true) return true;
	    else return false;
	}
	public void deleteWord(String word) {
		if(search(word)==false) return;
		Node current=root;
		for(char c:word.toCharArray()) {
			Node child=current.subNode(c);
			if(child.count==1) {
				current.childList.remove(child);
			}else {
				child.count--;
				current=child;
			}
		}
		current.isEnd=false;
	}
	public static void main(String[] args) {
		Trie trie = new Trie();
		trie.insert("ball");
		trie.insert("balls");
		trie.insert("sense");
	
		// testing deletion
		System.out.println(trie.search("balls"));
		System.out.println(trie.search("ba"));
		trie.deleteWord("balls");
		System.out.println(trie.search("balls"));
		System.out.println(trie.search("ball"));
	}
}
  • 实现朴素的字符串匹配算法
public class NaiveMatch {
	public static int NaiveMatch(String s,String d) {
		int i=0,j=0;
		while(i<s.length()&&j<d.length()) {
			if(s.charAt(i)==d.charAt(j)) {
				i++;
				j++;
			}else {
				i=i-(j-1);
				j=0;
			}	
		}
		if(j==d.length()) {
			return i-j;
		}
		return -1;
	}
}

LeetCode 151. Reverse Words in a String
LeetCode 344. Reverse String
LeetCode 8. String to Integer (atoi)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值