简体   繁体   中英

Check whether a given String is palindrome or not without using any library without loop

I was asked in an interview to write code to check if a given string is a palindrome or can be a palindrome by altering some character without using a library function. Here is my Approach

import java.util.Scanner;

public class Palindrom {
    static int  temp=0;
    static char[] cArr;
        static boolean chackPotentialPalindrom(char[] cAr){
            cArr=cAr;
            if(cArr!=null){
                char current=cArr[0];
                for(int i=1;i<cArr.length;i++){
                    if(current==cArr[i]){
                        cArr=removeElement(i);
                        chackPotentialPalindrom(cArr);
                        break;
                    } 
                    }
                if(cAr.length==2){
                if(cAr[0]==cAr[1]){
                    cArr=null;
                }}
                if(temp==0 && cArr!=null){
                    temp=1;
                    cArr=removeFirstElement(cArr);
                    chackPotentialPalindrom(cArr);
                    }
                }
            if(cArr==null){
                return true;
            }else{
                return false;
            }
        }
        static char[] removeFirstElement(char[] cAr){
            cArr=cAr;
            if(cArr!=null){
            if(cArr.length >1){
            char[] cArrnew=new char[cArr.length-1];
            for(int j=1,k=0;j<cArr.length;j++,k++){
                cArrnew[k]=cArr[j];
            }
            return cArrnew;
            } else {
                return null;
            }
                } else {
                    return null;
                }
        }
        static char[] removeElement(int i){
            if(cArr.length>2){
            char[] cArrnew=new char[cArr.length-2];
            for(int j=1,k=0;j<cArr.length;j++,k++){
                if(i!=j){
                    cArrnew[k]=cArr[j];
                }else{
                    k-=1;
                }
            }
            return cArrnew;}
            else{
                return null;
            }
        }
        public static void main(String[] args) {
            Scanner scn=new Scanner(System.in);
            while(true){
                temp=0;
            String s=scn.next();
            char[] arr=s.toCharArray();
            System.out.println(chackPotentialPalindrom(arr));
            }
        }
    }

Any tips to optimize this code?I could not write this in an interview as they have given a pen and paper to code.It took 3 hrs for me to write this. Can I be a developer?

Title says "without loop" but you need to check all symbol pairs, so using recursion, as you have tried, looks reasonable. But you don't check and use results of recursive calls.

Pseudocode might look like (note we don't need to change source data or extract substring):

Edit to provide possibility to alter one char

boolean checkPotentialPalindrom(char[] cAr, start, end, altcnt){
       if (end <= start)
             return true

       if (cAr[start] != cAr[end])
            altcnt = altcnt + 1

       if (altcnt > 1) 
             return false

       return checkPotentialPalindrom(cAr, start + 1, end - 1, altcnt)
 }

and make the first call with arguments 0, len(cAr-1), 0

Answering to your first question..You have to use recursion to solve this problem. Here is my approach.

public boolean isPalindrom(char[] str, int start, int end) {
    if (end <= start)
        return true;
    if (str[start] != str[end] || arraySize(str) <= 1)
        return false;
    return isPalindrom(str, start + 1, end - 1);
}

public int arraySize(char[] str) {
    int count = 0;
    for (char i : str) {
        count++;
    }
    return count;
}

You have tried to implement this algorithm using loops and you can simplify it like this

public boolean isPalindroms(char[] str) {
    int diffCount = 0;
    int left = 0;
    int right = arraySize(str) - 1;

    while (right > left) {
        if (str[right--] != str[left++]) {
            diffCount++;
        }
    }
    return (diffCount < 2);
}

public int arraySize(char[] str) {
    int count = 0;
    for (char i : str) {
        count++;
    }
    return count;
}

The answer for the second question that you have ask is definitely you can be a good developer. Computer programming is a Craft. Not Some Kind of Rocket Science. You have to master it by crafting it.

using recursive function

calling with left=0 and right = arr.length-1

public static boolean isPalindrom(char[] arr, int left, int right){
    if(arr[left++] != arr[right--])
        return false;
    if(left < right)
        isPalindromss(arr, left++, right--);
    return true;        
}


if you have to use while loop, you can simplify it like following

public boolean isPalindrom(char[] arr){
    int left=0;
    int right = arr.length-1;
    while(left < right){
        if(arr[left++] == arr[right--])
            continue;
        return false;
    }
    return true;
}


Using StringBuilder , We can do it

public static boolean isPalindrom(String str, int len){
    StringBuilder sb= new StringBuilder(str);       
    if((len > 1) & !(sb.substring(0,len/2 + 1).equals(sb.reverse().substring(0,len/2 + 1))))    
        return false;       
    return true;    
}

 function palin(input, leftIdx = 0, rightIdx = input.length - 1) { if (leftIdx >= rightIdx) return true; if (input[leftIdx] != input[rightIdx]) return false; return palin(input, leftIdx + 1, rightIdx - 1); } const testCases = { air: false, airia: true, caria: false, a: true, bb: true, bcdb: false, zzaaaaz: false, }; Object.keys(testCases).forEach(test => console.log("Test: ", test, " is palindrome: ", palin(test), testCases[test]) );

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