简体   繁体   English

检查是否可以使用递归将一个字符串转换为另一个字符串

[英]Check if it is possible to transform one string to another using recursion

I am trying to solve the below method by using recursion我正在尝试通过使用递归来解决以下方法

https://www.geeksforgeeks.org/check-possible-transform-one-string-another/ https://www.geeksforgeeks.org/check-possible-transform-one-string-another/

    static boolean abbreviation(String a, String b,int m, int n) {
    
    char[] x = a.toCharArray();
   
  
    if(m ==0|| n==0)
    return true;

    if(m==0 && n!=0)
    return false;

    if(n==0){
        for(int i=0; i < x.length; i++){
            
            //if any character is not in lower case, return false
            if( Character.isLowerCase( x[i] )){
                System.out.println(x[i]);
            return true;  
        
            }
        }
                
         return false;
    }
    if((a.charAt(m-1)==b.charAt(n-1))||
    (Character.toUpperCase(a.charAt(m-1))==b.charAt(n-1))){
       return abbreviation(a,b,m-1,n-1);
    }else return abbreviation(a,b,m-1,n) &&  abbreviation(a,b,m,n-1);
    

  
}

I am getting true instead of false for below inputs对于以下输入,我得到的是true而不是false

Input 1输入 1

AbCdE AbCDE

AFE模拟前端

Input 2输入 2

beFgH是FgH

EFG EFG

You have 3 cases when traversing characters of two string遍历两个字符串的字符有3种情况

  • Character matched (if lowercase then doing uppercase)字符匹配(如果小写则大写)
  • Charcter not matched and first string character is lowercase字符不匹配且第一个字符串字符为小写
  • Charcter not matched and first string character is uppercase字符不匹配且第一个字符串字符为大写

And base case if all character checked in first string then check all matched or not.和基本情况,如果所有字符都在第一个字符串中检查,则检查所有字符是否匹配。

  boolean abbreviation(String a, String b, int m, int n) {
    if (m == 0)
      return n == 0;

    if (n > 0 && Character.toUpperCase(a.charAt(m - 1)) == b.charAt(n - 1)) {
      return abbreviation(a, b, m - 1, n - 1);
    } else if(!Character.isUpperCase(a.charAt(m - 1))) {
      return abbreviation(a, b, m - 1, n);
    } else {
      return false;
    }
  }

Demo:演示:

System.out.println(abbreviation("AbCdE", "AFE", 5, 3));
System.out.println(abbreviation("beFgH", "EFG", 5, 3));
System.out.println(abbreviation("beFgh", "EFG", 5, 3));
System.out.println(abbreviation("daBcd", "ABC", 5, 3));

Output: Output:

false
false
true
true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM