Valid Palindrome Problem
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Example"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
NoteHave 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.
重点是.toLowerCase()和Character.isLetterOrDigit()两个函数的使用;
以及指针在标点情况下移动后的continue语句。
O(n) time without extra memory. ----> 指针嘛。
Solutionpublic class Solution { public boolean isPalindrome(String s) { if (s == null || s.length() < 2) { return true; } s = s.toLowerCase(); int start = 0, end = s.length() - 1; while (start < end) { if (!Character.isLetterOrDigit(s.charAt(start))) { start++; continue; } if (!Character.isLetterOrDigit(s.charAt(end))) { end--; continue; } if (s.charAt(start) != s.charAt(end)) { return false; } start++; end--; } return true; } }Update 2018-9
class Solution { public boolean isPalindrome(String s) { if (s == null || s.length() == 0) return true; s = s.trim().toLowerCase(); int i = 0, j = s.length()-1; while (i <= j) { while (i <= j && !((s.charAt(i) >= "a" && s.charAt(i) <= "z") || (s.charAt(i) >= "0" && s.charAt(i) <= "9"))) i++; while (i <= j && !((s.charAt(j) >= "a" && s.charAt(j) <= "z") || (s.charAt(j) >= "0" && s.charAt(j) <= "9"))) j--; if (i <= j && s.charAt(i++) != s.charAt(j--)) return false; } return true; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/65526.html
Problem Find the largest palindrome made from the product of two n-digit numbers. Since the result could be very large, you should return the largest palindrome mod 1337. Example Input: 2Output: 987Ex...
LeetCode version Problem Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, t...
public class Solution { public List binaryTreeToLists(TreeNode root) { List res = new ArrayList(); if(root == null) { return res; } Queue queue = new L...
摘要:找到开头的某个进行切割。剩下的部分就是相同的子问题。记忆化搜索,可以减少重复部分的操作,直接得到后的结果。得到的结果和这个单词组合在一起得到结果。 Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome...
摘要:自己没事刷的一些的题目,若有更好的解法,希望能够一起探讨项目地址 自己没事刷的一些LeetCode的题目,若有更好的解法,希望能够一起探讨 Number Problem Solution Difficulty 204 Count Primes JavaScript Easy 202 Happy Number JavaScript Easy 190 Reverse Bi...
阅读 1580·2021-11-23 09:51
阅读 1164·2019-08-30 13:57
阅读 2223·2019-08-29 13:12
阅读 1991·2019-08-26 13:57
阅读 1156·2019-08-26 11:32
阅读 915·2019-08-23 15:08
阅读 671·2019-08-23 14:42
阅读 3056·2019-08-23 11:41