/*
125. Valid Palindrome My Submissions Question
Total Accepted: 94559 Total Submissions: 401331 Difficulty: Easy
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
Hide Company Tags Microsoft Uber Facebook Zenefits
Hide Tags Two Pointers String
Hide Similar Problems (E) Palindrome Linked List
*/
public class IsPalindrome {
public static boolean isPalindrome(String s) {
/* O (n) time, O(1) space
The idead is simple, have two pointers - one at the head while teh other one at tail.
Move them towards each other until they meet while skippig non-aplphanumeric
characters.
Consider the case where given string contains only non-alphanumberic characters. This is
a valid palindrome because the empty string is also a valid palindrome.
*/
int i = 0, j = s.length() - 1;
while (i < j) {
while(i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;
while (i < j && ! Character.isLetterOrDigit(s.charAt(j))) j--;
if (Character.toLowerCase(s.charAt(i))
!= Character.toLowerCase(s.charAt(j))) {
return false;
}
i++; j--;
}
return true;
}
public static boolean isPalindrome_int(int x) {
if (x < 0) return false;
int p=x, q=0;
while(p>=10) {
q *=10; // q=0, q=10 q=120
q += p%10; // if x=1221, 1221%10 => q = 1, 122%10=2 q=12 q=120+2=122
p /=10; // p/10 => p= 122, p/10 => p=12 p =1
}
return (p == x%10 && q == x/10);
}
public static void main(String[] args) {
String str = "A man, a plan, a canal:Panama";
int x = 121;
int y = 1221;
int z = 12321;
int[] arr = {x, y,z};
System.out.printf("%s is Palindrome string: %b\n", str, isPalindrome(str));
for( int i : arr) {
System.out.println(isPalindrome_int(i));
}
}
}
125. Valid Palindrome My Submissions Question
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 虽然目前工作上不需要自己写算法,但还是想写点记录下什么。这里推荐个刷题网站LeetCode,如果你是个大学未毕业的...
- 题目:125. Valid Palindrome 不计非字母数字的元素和大小写,判断是否是回文字符串。 Given...
- 上海滩一直以来就是风云际会之所,在这里弱肉强食,适者生存。同时涌现出许多江湖大佬,诸如杜月笙、黄金荣、张啸林等等。...