LeetCode problem#125
Valid Palindrome
Solved in 2 languagesC#Java
Solution
32 lines
1public class Solution {
2 public bool IsPalindrome(string s) {
3 int i = 0;
4 int j = s.Length - 1;
5
6 while (i < j)
7 {
8 if (!Char.IsLetterOrDigit(s[i]))
9 {
10 i++;
11 }
12 if (!Char.IsLetterOrDigit(s[j]))
13 {
14 j--;
15 }
16 if (Char.IsLetterOrDigit(s[i]) && Char.IsLetterOrDigit(s[j]))
17 {
18 if (Char.ToLower(s[i]) != Char.ToLower(s[j]))
19 {
20 return false;
21 }
22 else
23 {
24 i++;
25 j--;
26 }
27 }
28 }
29
30 return true;
31 }
32}1class Solution {
2 // time O(n)
3 // space O(1)
4 public boolean isPalindrome(String s) {
5 int i = 0;
6 int j = s.length() - 1;
7
8 while (i < j) {
9 // 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.
10 char ci = Character.toLowerCase(s.charAt(i));
11 char cj = Character.toLowerCase(s.charAt(j));
12
13 if (!Character.isLetterOrDigit(ci)) {
14 i++;
15 }
16 else if (!Character.isLetterOrDigit(cj)) {
17 j--;
18 }
19 else if (ci != cj) {
20 return false;
21 }
22 else {
23 i++;
24 j--;
25 }
26 }
27 return true;
28 }
29}Want a walkthrough of this C# solution?
Get a step-by-step explanation of the idea behind the code.
Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.