比如说我有两个词。中国 和国人,(这个字符串是未知的,我只是举例),怎么判断这两个字符串中
都包含相同的内容,在上述例子中相同的内容就是“国”?最好不用数组,求大神指导!
遍历一个词的每个字符,判断当前遍历的字符另一个词是否包含。
这就是模式匹配啊,Java的string类提供了模式匹配的函数indexOf的。
hashmap要遍历所有的键,比较所有的值,算法复杂度n*m, 好像没有其他的办法了
在编码是统一的情况下,可以考虑判断String indexOf 是否为 -1;为-1就是没有。
http://blog.csdn.net/beiyeqingteng/article/details/6980474
参考
public static int[][] LCS(String str1, String str2) {
int[][] opt = new int[str2.length() + 1][str1.length() + 1];
for (int i = 0; i <= str2.length(); i++) {
opt[i][0] = 0;
}
for (int j = 0; j <= str1.length(); j++) {
opt[0][j] = 0;
}
for (int j = 1; j <= str1.length(); j++) {
for (int i = 1; i <= str2.length(); i++) {
if (str2.charAt(i-1) == str1.charAt(j-1)) {
opt[i][j] = opt[i-1][j-1] + 1;
} else {
opt[i][j] = ( opt[i-1][j] >= opt[i][j-1] ? opt[i-1][j] : opt[i][j-1]);
}
}
}
return opt;
}
public static void print(int[][] opt, String X, String Y, int i, int j) {
if (i == 0 || j == 0) {
return;
}
if (X.charAt(i - 1) == Y.charAt(j - 1)) {
System.out.print(X.charAt(i - 1));
print(opt, X, Y, i - 1, j - 1); // don't put this line before the upper line. Otherwise, the order is wrong.
}else if (opt[i - 1][j] >= opt[i][j]) {
print(opt, X, Y, i - 1, j);
} else {
print(opt, X, Y, i, j - 1);}
}