所以我一整天都试图解决这个任务,只是无法得到它.
以下函数接受2个字符串,第2个(不是第1个)可能包含*(星号).
*是字符串的替换(空,1个字符或更多),它可以出现(仅在s2中)一次,两次,更多或根本不存在,它不能与另一个*(ab ** c)相邻,无需检查.
public static boolean samePattern(String s1, String s2)
如果字符串具有相同的模式,则返回true.
它必须是递归的,不能使用任何循环,静态&全局变量.
可以使用局部变量&方法重载.
只能使用以下方法:charAt(i),substring(i),substring(i,j),length().
例子:
1:TheExamIsEasy; 2:* xamIs * y→true
1:TheExamIsEasy; 2:Th * mIsEasy *→true
1:TheExamIsEasy; 2:*→true
1:TheExamIsEasy; 2:TheExamIsEasy→true
1:TheExamIsEasy; 2:* IsHard→FALSE
我尝试使用charAt逐个比较字符,直到遇到星号,然后通过比较连续的char(i 1)和位置i的s1的char来检查星号是否为空,继续递归用i 1作为s2&的计数器我作为s1的反击者;
如果为false – 继续使用i 1递归作为两者的计数器.
继续此操作,直到找到另一个星号或字符串结尾.
我不知道,我的大脑失去了对事物的追踪,无法集中注意力,任何指针/提示?我正朝着正确的方向前进吗?
此外,有人告诉我们使用回溯技术来解决这个问题.
到目前为止我的代码(即使在理论上也不起作用):
public static boolean samePattern(String s1, String s2) {
if (s1.equals(s2) || s2 == "*") {
return true;
}
return samePattern(s1, s2, 1);
}
public static boolean samePattern(String s1, String s2, int i)
{
if (s1.equals(s2))
return true;
if (i == s2.length() - 1) // No *'s found -- not same pattern.
return false;
if (s1.substring(0, i).equals(s2.substring(0, i)))
samePattern(s1, s2, i+1);
else if (s2.charAt(i-1) == '*')
samePattern(s1.substring(0, i-1), s2.substring(0, i), 1); // new smaller strings.
else
samePattern(s1.substring(1), s2, i);
}