gpt4 book ai didi

java - 查找两个候选字符串列表之间的交集

转载 作者:行者123 更新时间:2023-11-30 04:37:07 24 4
gpt4 key购买 nike

我编写了以下Java代码,以查找String前缀后缀之间的交集> 在 Java 中。

// you can also use imports, for example:
// import java.math.*;
import java.util.*;
class Solution {
public int max_prefix_suffix(String S) {
if (S.length() == 0) {
return 1;
}
// prefix candidates
Vector<String> prefix = new Vector<String>();
// suffix candidates
Vector<String> suffix = new Vector<String>();
// will tell me the difference
Set<String> set = new HashSet<String>();

int size = S.length();
for (int i = 0; i < size; i++) {
String candidate = getPrefix(S, i);
// System.out.println( candidate );
prefix.add(candidate);
}

for (int i = size; i >= 0; i--) {
String candidate = getSuffix(S, i);
// System.out.println( candidate );
suffix.add(candidate);
}

int p = prefix.size();
int s = suffix.size();
for (int i = 0; i < p; i++) {
set.add(prefix.get(i));
}
for (int i = 0; i < s; i++) {
set.add(suffix.get(i));
}

System.out.println("set: " + set.size());
System.out.println("P: " + p + " S: " + s);
int max = (p + s) - set.size();
return max;
}

// codility
// y t i l i d o c
public String getSuffix(String S, int index) {
String suffix = "";
int size = S.length();
for (int i = size - 1; i >= index; i--) {
suffix += S.charAt(i);
}

return suffix;
}

public String getPrefix(String S, int index) {
String prefix = "";
for (int i = 0; i <= index; i++) {
prefix += S.charAt(i);
}

return prefix;
}

public static void main(String[] args) {
Solution sol = new Solution();
String t1 = "";
String t2 = "abbabba";
String t3 = "codility";

System.out.println(sol.max_prefix_suffix(t1));
System.out.println(sol.max_prefix_suffix(t2));
System.out.println(sol.max_prefix_suffix(t3));

System.exit(0);
}
}

一些测试用例是:

String t1 = "";
String t2 = "abbabba";
String t3 = "codility";

预期值为:

1, 4, 0

我的想法是生成前缀候选者并将它们插入 vector ,然后找到后缀候选者并将它们插入 vector ,最后将两个 vector 插入Set,然后计算差异。但是,我得到了 1、7 和 0。有人可以帮我弄清楚我做错了什么吗?

最佳答案

我将你的方法写如下:

public int max_prefix_suffix(String s) {
final int len = s.length();
if (len == 0) {
return 1; // there's some dispute about this in the comments to your post
}
int count = 0;
for (int i = 1; i <= len; ++i) {
final String prefix = s.substring(0, i);
final String suffix = s.substring(len - i, len);
if (prefix.equals(suffix)) {
++count;
}
}
return count;
}

如果您需要将前缀与后缀的反向进行比较,我会这样做:

final String suffix = new StringBuilder(s.substring(len - i, len))
.reverse().toString();

关于java - 查找两个候选字符串列表之间的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13220887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com