Check if the string is Palindrome

Given a string s, check if it is palindrome or not.

Check if the string is Palindrome




Example 1:
Input: S = "abba"
Output: 1
Explanation: S is a palindrome

Example 2:
Input: S = "abc" 
Output: 0
Explanation: S is not a palindrome


method 1:

step 1: store the reversed string in another string x.

step 2: compare the original string with the reversed string,if both are the same return1 else return 0.

implementation in c++:

        int isPlaindrome(string s)
	{
	    string x;  
        int n=s.length();
  
        for(int i=n-1;i>=0;i--)
          x=x+s[i];
      
        return s==x; //comparing if equal
	}

time complexity :O(n)



method 2:

1) Find length of string, let length be n.

2) Initialize low and high indexes as 0 and n-1 respectively.

3) Do following while low index ‘l’ is smaller than high index ‘h’.

   a) If str[l] is not same as str[h], then return false.

   b) Increment l and decrement h, i.e., do l++ and h–.

4) when l>=h the loop terminates and we have to return true


 implementation in c++:

void isPalindrome(char str[]) 
{ 
    // Start from leftmost and rightmost corners of str 
    int l = 0; 
    int h = strlen(str) - 1; 
  
    // Keep comparing characters while they are same 
    while (h > l) 
    { 
        if (str[l++] != str[h--]) 
        return 0;
    } 
    return 1;
} 

time complexity :O(n)


No comments

darkmode