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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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...
閱讀 1608·2021-11-23 09:51
閱讀 1178·2019-08-30 13:57
閱讀 2257·2019-08-29 13:12
閱讀 2011·2019-08-26 13:57
閱讀 1193·2019-08-26 11:32
閱讀 978·2019-08-23 15:08
閱讀 699·2019-08-23 14:42
閱讀 3079·2019-08-23 11:41