Leetcode / 125. Valid Palindrome
Pick a programming language:
Here is the source code for the solution to this problem.
public class Solution {
public bool IsPalindrome(string s) {
int i = 0;
int j = s.Length - 1;
while (i < j)
{
if (!Char.IsLetterOrDigit(s[i]))
{
i++;
}
if (!Char.IsLetterOrDigit(s[j]))
{
j--;
}
if (Char.IsLetterOrDigit(s[i]) && Char.IsLetterOrDigit(s[j]))
{
if (Char.ToLower(s[i]) != Char.ToLower(s[j]))
{
return false;
}
else
{
i++;
j--;
}
}
}
return true;
}
}
class Solution {
// time O(n)
// space O(1)
public boolean isPalindrome(String s) {
int i = 0;
int j = s.length() - 1;
while (i < j) {
// The String.toLowerCase() method in Java has a time complexity of O(n), where n is the length of the string. Given n is always 1, O(1) here.
char ci = Character.toLowerCase(s.charAt(i));
char cj = Character.toLowerCase(s.charAt(j));
if (!Character.isLetterOrDigit(ci)) {
i++;
}
else if (!Character.isLetterOrDigit(cj)) {
j--;
}
else if (ci != cj) {
return false;
}
else {
i++;
j--;
}
}
return true;
}
}
Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: