有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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


共 (3) 个答案

  1. # 1 楼答案

    以下是我的片段:

    def checkAB(str):
        if len(str) == 0:
            return True
        if len(str) == 1:
            if str == 'a':
                return True
            else:
                return False
        if str[0] == 'a':
            return checkAB(str[1:])
        elif str[0] == 'b':
            if str[1] == 'b':
                return checkAB(str[2:])
            else:
                return False
        else:
            return False
    

    尝试读取布尔值并以字符串“true”或“false”打印输出。在我的例子中,我犯了一个错误,直接返回布尔值

    还有一个片段:

    def checkAB(str):
        if (len(str) == 0):
            return True
    
        if (str[0] == 'a'):
            if (len(str[1:]) > 1 and str[1:3] == 'bb'):
                return checkAB(str[3:])
            else:
                return checkAB(str[1:])
        else:
            return False
    

    我希望这对你有帮助

  2. # 2 楼答案

    如果允许使用正则表达式,则模式(a+(bb)?)+将匹配遵循规则的字符串(而不匹配不遵循规则的字符串)

    否则,如果没有某种循环,您的方法可能无法工作,因为字符串aaaaaaaaaaa与模式匹配

    考虑下面的方法,应该处理它。

    private static boolean stringMatches(String s) {
      // Handle empty and null cases first.
      if (s == null || s.isEmpty()) return false;
    
      // So long as the string continues to match the pattern, keep stripping
      // characters from it until it is empty. If you reach empty, it matches the pattern.
      while (! s.isEmpty()) {
        // If the first character isn't 'a', we don't match; return false.
        if (s.charAt(0) != 'a') {
          return false;
        }
    
        // Check for abb, if so strip all of that, otherwise strip just the a
        if (s.length() >= 3 && "abb".equals(s.substring(0,3)) {
          s = s.substring(3);
        } else {
          s = s.substring(1);
        }
      }
      // Reached empty string, return true.
      return true;
    }
    
  3. # 3 楼答案

    这是递归方法:

    public static boolean checkAB(String s) 
    {
        if (s.length()==0) 
            return true;
        if (s.charAt(0) != 'a')
            return false;
        if (s.length() >= 3 && "abb".equals(s.substring(0,3)))
            return checkAB(s.substring(3));
        else
            return checkAB(s.substring(1));
    }