字典树模板题

题目
该题给出了若干个字符串,判断某个串是否另一个串的子串

暴力方法,AC代码:

import java.io.*;
import java.math.*;
import java.math.BigInteger;
import java.util.*;
public class Main{
	static char s[][];
	public static boolean judge(int n){//判断
	    int i,j,m;
	    for(i=0;i<n-1;i++){
	        m=s[i].length;
	        for(j=0;j<m;j++){
	            if(s[i][j]!=s[i+1][j])
	                break;
	        }
	        if(j==m)
	            return false;
	    }
	    return true;
	}
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
	    int t,n;
	   for(t=sc.nextInt();t>0;t--) {
		    s=new char[10005][26];
	    	n=sc.nextInt();
	    	String str[]=new String[n];
	    	for(int i=0;i<n;i++) {
	    		str[i]=sc.next();
	    	}
	        Arrays.sort(str);//按字典序排序
	        for(int i=0;i<n;i++) {
	        	s[i]=str[i].toCharArray();
	        }
	        if(judge(n))
	          System.out.println("YES");
	        else
	          System.out.println("NO");
	    }
	}
}

字典树:

import java.io.*;
import java.math.*;
import java.math.BigInteger;
import java.util.*;
class TreeNode{
	final static int MAX_SIZE=26;
	char date;		//表示当前节点存的字母
	boolean isEnd = false;	//表示是否为叶子节点
	TreeNode []childs;		//表示子节点
	
	public TreeNode() {
		childs = new TreeNode[MAX_SIZE];//因为英文最多26个字母
		isEnd=false;
	}
}


public class Main {
	public static void createTireTree(TreeNode node,String str) {//插入
		char d[]=str.toCharArray();
		for(int i=0;i<d.length;i++) {
			int loc =d[i]-'0';		//转化0~25之间的数字
			if(node.childs[loc]==null) {
				node.childs[loc]=new TreeNode();
				node.childs[loc].date=d[i];
			}
			node=node.childs[loc];//递归
		}
		node.isEnd=true;
	}
	public static boolean find(String str,TreeNode node) {
		char d[]=str.toCharArray();
		for(int i=0;i<d.length;i++) {
			int loc =d[i]-'0';
			if(node.childs[loc]!=null) {
				node = node.childs[loc];
			}else {
				return false;
			}
		}
		return true;
		//return node.isEnd;
	}
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		for(int t=sc.nextInt();t>0;t--) {
			TreeNode root = new TreeNode();
			boolean bool=true;;
			int n=sc.nextInt();
			String str[]=new String[n];
			for(int i=0;i<n;i++) {
				str[i]=sc.next();
			}
			Arrays.sort(str);
			for(int i=n-1;i>=0;i--) {
				//System.out.println(str[i]);
				if(find(str[i],root))bool=false;
				createTireTree(root,str[i]);
			}
			//System.out.println(find("911",root));
			if(bool)System.out.println("Yes");
			else System.out.println("No");
		}
	}
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值