我編寫了以下Java
代碼,找到Java
的prefix
和suffix
的String
之間的交集。查找兩個候選字符串列表之間的交集
// 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
我的想法是產生prefix
候選人,並將其推入一個矢量,然後找到suffix
候選人並將他們推入vector
,最後將vectors
推入Set
,然後計算差異。但是,我得到1, 7, and 0
。有人能幫我弄清楚我做錯了什麼嗎?
有些無關,但請參閱:http://stackoverflow.com/questions/1386275/why-is-java-vector-class-considered-obsolete-or-deprecated – NullUserException
這是什麼與學生和'矢量'? ?課程筆記*是否已更新? (你永遠不要使用'Vector' - 它壞了!) – Bohemian
「abbabba」是一個迴文,所以每個前綴都是後綴。爲什麼不是預期值7? –