遇到递归问题。不断得到不正确的输出

问题描述 投票:0回答:1

在外星种族的语言中,所有单词都采用 Blurbs 的形式。简介 是 Whoozit 后接一个或多个 Whatzits。 Whoozit 是一个角色 “x”后跟零个或多个“y”。 Whatzit 是一个“q”,后跟一个 'z' 或 'd',后跟 Whoozit。

设计并实现一个递归程序来判断一个字符串是否是一个 有效的简介。用户应该能够输入一个字符串,并且程序 应该打印该字符串是否是 Blurb(“true”或“false”)。

我一直在努力解决这个问题,并得出了这段代码作为我能得到的最接近答案:

import java.util.Scanner;

public class Blurb {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a string to find out whether it is a blurb:");
        String input = scanner.nextLine();
        boolean isValid = isValidBlurb(input);
        System.out.println(isValid);
        scanner.close();
    }

    public static boolean isValidBlurb(String str) {
        if (str.isEmpty()) {
            return false; // Empty string is not a valid Blurb
        }

        // Check if the string starts with 'x', which is always a Whoozit
        if (str.charAt(0) == 'x') {
            return isValidWhoozit(str.substring(1)); // Check the rest of the Blurb
        }

        return false; // Invalid start of a Blurb
    }

    private static boolean isValidWhoozit(String str) {
        if (str.isEmpty()) {
            return true; // Empty Whoozit is valid in a Blurb
        }

        // Check if the string starts with 'y' or 'qz' or 'qd' and recursively call isValidWhoozit
        if (isValidWhatzit(str)) {
            return isValidWhoozit(str.substring(3)); // Continue checking the rest of the Whoozit
        } else if (str.charAt(0) == 'y') {
            return isValidWhoozit(str.substring(1)); // Continue checking the rest of the Whoozit
        }

        return false; // Invalid Whoozit
    }

    private static boolean isValidWhatzit(String str) {
        if (str.length() >= 3) {
            String prefix = str.substring(0, 3);
            return prefix.equals("qz") || prefix.equals("qd");
        }
        return false;
    }
}

假设从键盘输入以下内容: xyyyy 您显示: 输入字符串判断是否是blurb:true

而不是: 输入字符串判断是否为blurb:false

它一直将这个“xyyy”视为正确,但我不确定我做错了什么。

java
1个回答
0
投票

我建议尝试不使用递归的算法:

public static boolean isValidBlurb(String str) {
   
   // Find the initial x
    int i = 0;
    if (str.isEmpty() || str.charAt(i) != 'x') {
        return false; // Must start with 'x'
    }
    i++; // Skip 'x'
    while (i < str.length() && str.charAt(i) == 'y') {
        i++; // Skip all 'y'
    }

    // Must have at least one Whatzit following the initial Whoozit
    if (i == str.length()) {
        return false; // No Whatzit found
    }

   
    while (i < str.length()) { 
     `Check for one or more Whatzits in this loop`    
    }
  
    return true; // All conditions met
}
© www.soinside.com 2019 - 2024. All rights reserved.