假设我们有一个包含这些字符的字符串 “ABGCCFFGTBG”
然后我们有另一个包含字符“GECCCDOABG”的字符串
所以模式是前缀和后缀,但如果你给定的字符串比这个大,但有共同的前缀和后缀模式,如何将它们拉出到java中的子字符串中。请记住,我们并不总是知道字符串中的字符正在获取,我们只是知道其中存在某种模式。
我的开始是这样的
for(int i = 0. i < strA.length(); i++)
{
for(int j = 0; j < strB.length(); j++)
{
if(strA.charAt(i) == strB.charAt(j))
{
String subPattern = strA.substring(0,i);
String subPattern2 = strB.substring(0,j);
}
}
}
但这不起作用。有什么想法吗?
最佳答案
首先尝试选择最匹配的模式:
public static void main(String[] args) {
String strA = "ABGCCFFGTBG";
String strB = "GECCCDOABG";
System.out.println("Pattern: " + findPattern(strA, strB));
}
public static String findPattern(String strA, String strB) {
for (int length = Math.min(strA.length(), strB.length()); length > 0; length--) {
for (int i = 0; i <= strA.length() - length; i++) {
String pattern = strA.substring(i, i + length);
if (strB.contains(pattern)) {
return pattern;
}
}
}
throw new NoSuchElementException("No common pattern between " + strA + " and " + strB);
}
输出:
Pattern: ABG
关于java - 使用基本 Java 方法查找字符串中的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26959566/