简体   繁体   中英

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/

    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

Input 1

AbCdE

AFE

Input 2

beFgH

EFG

You have 3 cases when traversing characters of two string

  • 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:

false
false
true
true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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