Leet Code OJ 125. Valid Palindrome [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.
翻譯:
給定一個字符串,檢測它是否是回文對稱的,只考慮其中字母與數字的字符。
例如”A man, a plan, a canal: Panama”是回文對稱的,”race a car”不是。
提示:你考慮過字符串可能是空的情況嗎?這是一個面試中應該問出的好問題。為了處理這個問題,我們假定空串是回文對稱的。
分析:
直接遍歷比較是很困難的,我們需要先進行過濾(大寫轉小寫)。過濾后只要將前后對應位置的字符直接比較就可以了。過程中要注意有的時候會涉及char和int的強轉。
Java版代碼:
public class Solution {public boolean isPalindrome(String s) {char[] charArr=s.toCharArray();List<Integer> list=new ArrayList<>();int fix='a'-'A';for(char c:charArr){if((c>='a'&&c<='z')||(c>='0'&&c<='9')){list.add((int)c);}else if(c>='A'&&c<='Z'){list.add(c+fix);}}int size=list.size();for(int i=0;i<size/2;i++){if(list.get(i)!=list.get(size-1-i)){return false;}}return true;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 125. Valid Palindrome [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 20. Val
- 下一篇: jedisPool.getResourc