Alg.10 Palindrome Check

From algoexpert.io

A palindrome is a string that’s written the same forward and backward. For this problem, we need to write a function to determine whether a string is palindrome

The code implementation is pretty straightforward, we use two pointers, they point to the start and end of the string. Then, we check if the characters are the same until we reach the midpoint of the string.

Here is the code implementation

1
2
3
4
5
6
7
8
9
10
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left <= right) {
if (str.charAt(left) != str.charAt(right)) return false;
left++;
right--;
}
return true;
}

Time complexity: O(n); Space complexity: O(1)

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2021 Zirun Lin

Thanks~

支付宝
微信