我希望在源字符串中搜索一个序列,但是该序列可能允许插入。例如,序列:AG ** GC最多允许两个插入,并且将匹配AGGC或AGTGC或AGTTGC等。
我已经尝试了用Java开发动态编程方法,但是似乎无法使其在指定数量的*下工作。该程序不区分一个*和两个*。因此,如果我输入*,则允许任意数量的插入。
有人对如何使*仅指定一个字符有建议吗?
import java.util.Arrays;
public class GFG{
// Function that matches input str with
// given wildcard pattern
static boolean strmatch(String str, String pattern,
int n, int m)
{
// empty pattern can only match with
// empty string
if (m == 0)
return (n == 0);
// lookup table for storing results of
// subproblems
boolean[][] lookup = new boolean[n + 1][m + 1];
// initailze lookup table to false
for(int i = 0; i < n + 1; i++)
Arrays.fill(lookup[i], false);
// empty pattern can match with empty string
lookup[0][0] = true;
// Only '*' can match with empty string
for (int j = 1; j <= m; j++)
if (pattern.charAt(j - 1) == '*')
lookup[0][j] = lookup[0][j - 1];
// fill the table in bottom-up fashion
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
// Two cases if we see a '*'
// a) We ignore '*'' character and move
// to next character in the pattern,
// i.e., '*' indicates an empty sequence.
// b) '*' character matches with ith
// character in input
if (pattern.charAt(j - 1) == '*')
lookup[i][j] = lookup[i][j - 1] ||
lookup[i - 1][j];
// Current characters are considered as
// matching in two cases
// (a) current character of pattern is '?'
// (b) characters actually match
else if (pattern.charAt(j - 1) == '?' ||
str.charAt(i - 1) == pattern.charAt(j - 1))
lookup[i][j] = lookup[i - 1][j - 1];
// If characters don't match
else lookup[i][j] = false;
}
}
return lookup[n][m];
}
public static void main(String args[])
{
String str = "baabab";
String pattern = "ba**********ab";
// String pattern = "ba*****ab";
// String pattern = "ba*ab";
// String pattern = "a*ab";
// String pattern = "a*****ab";
// String pattern = "*a*****ab";
// String pattern = "ba*ab****";
// String pattern = "****";
// String pattern = "*";
// String pattern = "aa?ab";
// String pattern = "b*b";
// String pattern = "a*a";
// String pattern = "baaabab";
// String pattern = "?baaabab";
// String pattern = "*baaaba*";
if (strmatch(str, pattern, str.length(),
pattern.length()))
System.out.println("YES");
else
System.out.println("No");
}
}