LeetCode OJ: 125. Valid Palindrome 迴文判斷
題目連結 https://leetcode.com/problems/valid-palindrome/ 。 此題和 a022: 迴文 、 a038: 數字翻轉 、 LeetCode OJ: 9. Palindrome Number 迴文數字 類似。但本次要用Java String 的函數 reverse() 來解。先將非英文字母與數字給刪除,並轉成小寫,之後就可以呼叫 reverse() 做翻轉為 rev 字串,並和原字串 actual 比較是否相同。 程式碼: 1 2 3 4 5 6 7 public class Solution { public boolean isPalindrome ( String s ) { String actual = s . replaceAll ( "[^A-Za-z0-9]" , "" ). toLowerCase (); String rev = new StringBuffer ( actual ). reverse (). toString (); return actual . equals ( rev ); } } 若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。 If you like this post, please click the ads on the blog or buy me a coffee . Thank you very much.