# LeetCode算法题-Longest Palindrome（五种解法）

### 02 第一种解法

public int longestPalindrome(String s) {
int[] arr = new int[256];
for (int i=0; i<s.length(); i++) {
arr[s.charAt(i)]++;
}
int count = 0;
int single = 0;
for (int j=0; j<arr.length; j++) {
if (arr[j]%2 == 0) {
count += arr[j];
} else {
count += arr[j]-1;
single = 1;
}
}
return count+single;
}

### 03 第二种解法

public int longestPalindrome2(String s) {
int[] arr = new int[256];
for (int i=0; i<s.length(); i++) {
arr[s.charAt(i)]++;
}
int count = 0;
for (int j=0; j<arr.length; j++) {
count += (arr[j]/2)*2;
if (arr[j]%2 == 1 && count%2 == 0) {
count++;
}
}
return count;
}

### 04 第三种解法

public int longestPalindrome3(String s) {
int[] arr = new int[256];
for (int i=0; i<s.length(); i++) {
arr[s.charAt(i)]++;
}
int count = 0;
for (int j=0; j<arr.length; j++) {
count += (arr[j]/2)*2;
}
return count == s.length() ? count : count+1;
}

### 05 第四种解法

public int longestPalindrome4(String s) {
Set<Character> set = new HashSet<Character>();
int count = 0;
for (int i=0; i<s.length(); i++) {
if (set.contains(s.charAt(i))) {
count = count + 2;
set.remove(s.charAt(i));
} else {
}
}
if (!set.isEmpty()) {
count = count + 1;
}
return count;
}

### 06 第五种解法

public int longestPalindrome5(String s) {
int[] arr = new int[58];
int count = 0;
for (char ch : s.toCharArray()) {
if (arr[ch-'A'] == 0) {
arr[ch-'A']++;
} else {
arr[ch-'A']--;
count += 2;
}
}
for (int j=0; j<arr.length; j++) {
if (arr[j] > 0) {
count += 1;
break;
}
}
return count;
}

### 07 小结

posted @ 2019-01-04 08:37  程序员小川  阅读(...)  评论(...编辑  收藏