Valid Palindrome LeetCode

 Approach 1: Using Inbuilt reverse() Function on StringBuffer Object.


        s=s.replaceAll("[^a-zA-Z0-9]", "");//replace all non alphanumeric characters with empty string.

        s=s.toLowerCase();

       

        StringBuffer sb=new StringBuffer();

        sb.append(s);

        String s2=sb.reverse().toString();

        if(s.equals(s2)){

            return true;

        }

        else{

            return false;

        }


Time: O(N) [As do swapping of characters by iterating up to half of the length of  given string length.][LeetCode Time: 23 ms beats 30.26% ]

Space: O(Length of String)[LeetCode Memory: 40MB beats 32.77%]



=========================================================================


Approach 2: Using Two Pointers


        s=s.replaceAll("[^a-zA-Z0-9]", "");

        s=s.toLowerCase();

        

        int start=0;

        int count=0;

        int end=s.length()-1;

        if(start==end || s.length()==0){

            return true;

        }

        else{

        

        while(start<end){

                if(String.valueOf(s.charAt(start)).equals(String.valueOf(s.charAt(end)))){


                    count++;


                }


                else{

                    count=0;

                break;

                }

                start++;

                end--;

            }

            if(count!=0){


                return true;

            }

            else{


                return false;

            }

        }


Time:O(N)[traverse till half comparing both values one from the start and one from the end.][LeetCode Time:24ms beats 28.81%]

Space:O(1)[Not storing any value][LeetCode Memory : 40.3MB beats 20.01% ]



Thanks For Reading.😇


























Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks