public boolean isPalindrome(String s) { return this.reverse(s).equals(s); }
public String reverse(String s) { StringBuilder ans = new StringBuilder(); for (char i : s.toCharArray()) { ans.insert(0, i); } return ans.toString(); }
1 2 3 4 5 6 7 8
public boolean isPalindrome(String s) { return StringUtils.reverse(s).equals(s); }
// StringUtils.reverse(s)的底层为 public static String reverse(String str) { return str == null ? null : (new StringBuilder(str)).reverse().toString(); }
算法二
图解
解释
第一位为Left, 最后一位为Right Left == Right, Left + 1 == Right - 1, …
1 2 3 4 5 6 7 8 9 10 11 12 13
public boolean isPalindrome(String s) { int left = 0; int right = s.length() - 1; char[] chars = s.toCharArray(); while (left < right) { if (chars[left] != chars[right]) { return false; } left++; right--; } return true; }
算法三
1 2 3 4 5 6 7 8 9 10
public boolean isPalindrome(String s) { int length = s.length(); char[] chars = s.toCharArray(); for (int i = 0; i < length / 2; i++) { if (chars[i] != chars[length - 1 - i]) { return false; } } return true; }
算法四
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public boolean isPalindrome(String s) { char[] chars = s.toCharArray(); Stack<String> stack = new Stack<>(); for (char c : chars) { stack.push(String.valueOf(c)); } for (char c : chars) { String x = stack.pop(); if(!StringUtils.equals(x, String.valueOf(c))) { return false; } } return true; }