2 回答
![?](http://img1.sycdn.imooc.com/54584cde0001d19202200220-100-100.jpg)
TA贡献1873条经验 获得超9个赞
关于如何解决这个问题,基本上有两种基本方法:
For-对列表和每个字符的每次迭代
你离这个人很近。干得好:
int maxLength = 0;
int indexOfLongestMatch = -1;
for (int i = 0; i < stringList.size(); i++) { // Iterate the List
String string = stringList.get(i);
int maxIndex = Math.min(wordA.length(), string.length()); // Compare lengths
if (maxIndex >= maxLength) { // Worth to continue?
int commonLength = 0;
for (int j = 0; j < maxIndex; j++) { // Iterate characters
if (string.charAt(j) == wordA.charAt(j)) {
commonLength++; // Any match counts
if (commonLength >= maxLength) { // Check for the new max
maxLength = commonLength; // Register it
indexOfLongestMatch = i; // New index of the max
}
}
}
}
}
中最长匹配词的索引stringList是indexOfLongestMatch(等于2根据您提供的相同输入)和词是stringList.get(indexOfLongestMatch)( 6301)。
正则表达式。正如@YCF_L 在这里建议的那样,另一种可能的方法是 Regex,它可以帮助您仅匹配具有使用模式的公共初始字符的字符串:
6?3?0?1?0?2?
要从输入中实现此模式,您必须将每个字符替换.为$0?,其中$0任何与点匹配的匹配字符.。在Regex101 上演示
Pattern pattern = Pattern.compile(wordA.replaceAll(".", "$0?"));
然后您只需在列表上使用一次迭代找到最长匹配的字符串及其索引:
Matcher matcher;
int indexOfLongestMatch = -1;
int maxLength = 0;
for (int i = 0; i < stringList.size(); i++) { // Iterate the List
matcher = pattern.matcher(stringList.get(i)); // Apply the pattern
if (matcher.matches()) { // Has a match?
int length = matcher.group(0).length();
if (length >= maxLength) { // Check for the new max
maxLength = length; // Register it
indexOfLongestMatch = i; // New index of the max
}
}
}
结果与上面的示例相同。indexOfLongestMatch是找到的索引。
请注意,默认情况下,结果索引设置为-1列表中不存在的索引 - 这意味着没有任何字符串以您想要的方式与输入匹配。
![?](http://img1.sycdn.imooc.com/5333a1bc00014e8302000200-100-100.jpg)
TA贡献1876条经验 获得超7个赞
据我了解,您想返回值,该值与您的单词最常见。这是我对您的问题的解决方案:
String wordA = "630677";
List<String> stringList = new ArrayList<>();
stringList.add("630507"); //1st
stringList.add("630622"); //2nd
stringList.add("6301"); //3rd
stringList.add("63"); //4th
String common = "";
int commonCount = 0;
int highestCount = 0;
for(String s : stringList)
{
for(int i = 0; i < wordA.length(); i++) {
if(s.length() > i && s.charAt(i) == wordA.charAt(i)) {
commonCount++;
}
if(s.length() <= i || s.charAt(i) != wordA.charAt(i) || wordA.length() <= i + 1) {
if(commonCount > highestCount) {
highestCount = commonCount;
common = s;
}
commonCount = 0;
break;
}
} }
System.out.println(common.isEmpty() ? "There is no common." : "common is: " + common);
}
编辑:请注意,这将始终返回列表中的第一个字符串,以防有更多字符串具有相同数量的正确字符。
添加回答
举报