class Solution {
public int longestCommonPrefix(int[] arr1, int[] arr2) {
Set<String> set = new HashSet<>();
for(int x : arr1){
String t = String.valueOf(x);
for(int i=1; i<=t.length(); i++)
set.add(t.substring(0,i));
}
int ans = 0;
for(int x : arr2){
String t = String.valueOf(x);
for(int i=1; i<=t.length(); i++)
if(set.contains(t.substring(0,i)))
ans = Math.max(ans, i);
}
return ans;
}
}
又因为题目中给的数据都是整形,所以我们也可以通过存储数字来匹配,这样可以节省一点时间,代码如下:
复制代码
class Solution {
public int longestCommonPrefix(int[] arr1, int[] arr2) {
Set<Integer> set = new HashSet<>();
for(int x : arr1){
for(; x>0; x/=10)
set.add(x);
}
int ans = 0;
for(int x : arr2){
for(; x>0; x/=10){
if(set.contains(x)){
ans = Math.max(ans, x);
break;
}
}
}
return ans>0?String.valueOf(ans).length():0;
}
}
class Solution {
static class Node{
Node[] son = new Node[26];
int cnt;
}
public long countPrefixSuffixPairs(String[] words) {
long ans = 0;
Node root = new Node();//前缀字典树
for(String T : words){
char[] t = T.toCharArray();
int n = t.length;
//z函数实现
int[] z = new int[n];
z[0] = n;
int l=0,r=0;
for(int i=1; i<n; i++){
if(i <= r) z[i] = Math.min(z[i-l], r-i+1);
while(i+z[i]<n && t[z[i]] == t[i+z[i]]){
l = i;
r = i+z[i];
z[i]++;
}
}
//字典树实现,边比较边建立字典树
Node cur = root;
for(int i=0; i<n; i++){
if(cur.son[t[i]-'a']==null)
cur.son[t[i]-'a'] = new Node();
cur = cur.son[t[i]-'a'];
if(z[n-1-i] == i+1)//判断前后缀相同
ans += cur.cnt;
}
cur.cnt++;
}
return ans;
}
}
class Solution {
static class Node{
Map<Integer, Node> son = new HashMap<>();
int cnt;
}
public long countPrefixSuffixPairs(String[] words) {
long ans = 0;
Node root = new Node();
for(String T : words){
char[] t = T.toCharArray();
int n = t.length;
Node cur = root;
for(int i=0; i<n; i++){
//数据最大是10^5,使用整数代替 (a,b)
int p = (t[i]-'a')<<5 | (t[n-1-i]-'a');
if(cur.son.getOrDefault(p,null)==null)
cur.son.put(p,new Node());
cur = cur.son.get(p);
ans += cur.cnt;
}
cur.cnt++;
}
return ans;
}
}