题目
Given n strings and a target string, output the maximum length of the longest common prefix of the target string with the given n strings.
example
Give [“abcba”,”acc”,”abwsf”],target = “abse”,return 2.
Explanation:
The longest common prefix of “abse” and “abcba” is “ab”, and the length is 2. The longest common prefix of “abse” and “acc” is “a”, and the length is 1. The longest common prefix of “abse” and “abwsf” is “ab”, and the length is 2. max(2,1,2) = 2.
Give [“aaa”,”bbb”,”aabb”],target = “aaab”,return 3.
Explanation:
The longest common prefix of “aaab” and “aaa” is “aaa”, and the length is 3. The longest common prefix of “aaab” and “bbb” is “”, and the length is 0. The longest common prefix of “aaab” and “aabb” is “aa”, and the length is 2. max(3,0,2) = 3.
答案
public class Solution {
/**
* @param dic: the n strings
* @param target: the target string
* @return: The ans
*/
public int the_longest_common_prefix(List<String> dic, String target) {
// write your code here
int res = 0;
for (int i = 0; i < dic.size(); i++) {
for (int j = Math.min(dic.get(i).length(), target.length()); j >= 0; j--) {
String temp = dic.get(i).substring(0, j);
if (target.substring(0, j).equals(temp)) {
if(j > res) {
res = j;
}
}
}
}
return res;
}
}