java检查字符串是否使用规定的规则集形成
检查字符串是否使用规定的规则集形成。使用以下规则生成:
a. the string begins with an 'a'
b. each 'a' is followed by nothing or an 'a' or "bb"
c. each "bb" is followed by nothing or an 'a'
我尝试了以下代码:
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String str = scn.nextLine();
boolean b = false;
if (str.charAt(0) == 'a') {
if (str.charAt(1) == 'b') {
if (str.charAt(2) == 'b') {
b = true;
} else
b = false;
} else
b = false;
} else
b = false;
System.out.println(b);
}
代码正确吗。。。??? 对于input=aab,输出应为false;对于input=abba,输出应为true
# 1 楼答案
以下是我的片段:
尝试读取布尔值并以字符串“true”或“false”打印输出。在我的例子中,我犯了一个错误,直接返回布尔值
还有一个片段:
我希望这对你有帮助
# 2 楼答案
如果允许使用正则表达式,则模式
(a+(bb)?)+
将匹配遵循规则的字符串(而不匹配不遵循规则的字符串)否则,如果没有某种循环,您的方法可能无法工作,因为字符串
aaaaaaaaaaa
与模式匹配考虑下面的方法,应该处理它。
# 3 楼答案
这是递归方法: