How to check if a string is a palindrome
A
palindrome
is astring
that reads the same backward as forward. For instance,level
,baab
To check if a string is a palindrome, you can reverse it and compare it with the original one.
- if the
reversed string
is equal to the original. It means theinput string
is apalindrome
.
Another approach would be to compare characters from both sides, one by one.
- if all characters are equal, the
input string
is apalindrome
.
Code
public bool IsPalindrome(string value)
{
int left = 0;
int right = value.Length - 1;
while (left < right)
{
if (value[left] != value[right])
{
return false;
}
left++;
right--;
}
return true;
}
The time complexity is O(n)
.
Recent articles
Nice to read