File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
src/main/java/com/leetcode/strings Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .leetcode .strings ;
2+
3+ /**
4+ * @author rampatra
5+ * @since 2019-04-19
6+ */
7+ public class ValidPalindrome {
8+
9+ /**
10+ * Time complexity: O(n)
11+ * where,
12+ * n = no. of characters in the string
13+ * <p>
14+ * Runtime: <a href="https://leetcode.com/submissions/detail/223590134/">2 ms on leetcode</a>.
15+ *
16+ * @param str
17+ * @return
18+ */
19+ private static boolean isPalindrome (String str ) {
20+ char [] chars = str .toCharArray ();
21+ int left = 0 ;
22+ int right = chars .length - 1 ;
23+
24+ while (left < right ) {
25+ // if it's not alphanumeric then move the left pointer forward
26+ while (!isAlphaNumeric (chars [left ]) && left < right ) {
27+ left ++;
28+ }
29+ // if it's not alphanumeric then move the right pointer backward
30+ while (!isAlphaNumeric (chars [right ]) && left < right ) {
31+ right --;
32+ }
33+
34+ // case insensitive comparison
35+ if (Character .toLowerCase (chars [left ]) != Character .toLowerCase (chars [right ])) {
36+ return false ;
37+ }
38+
39+ left ++;
40+ right --;
41+ }
42+
43+ return true ;
44+ }
45+
46+ private static boolean isAlphaNumeric (char c ) {
47+ int i = (int ) c ;
48+ return (i >= 48 && i <= 57 ) || (i >= 65 && i <= 90 ) || (i >= 97 && i <= 122 );
49+ }
50+
51+ public static void main (String [] args ) {
52+ System .out .println (isPalindrome ("A man, a plan, a canal: Panama" ));
53+ System .out .println (isPalindrome ("race a car" ));
54+ System .out .println (isPalindrome ("0P" ));
55+ }
56+ }
You can’t perform that action at this time.
0 commit comments