题目
该题给出了若干个字符串,判断某个串是否另一个串的子串
暴力方法,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");
}
}
}