当前位置:网站首页>Leetcode- longest palindrome string - simple
Leetcode- longest palindrome string - simple
2022-06-13 05:49:00 【AnWenRen】
title :409 Longest palindrome - Simple
subject
Given a string of uppercase and lowercase letters , Find the longest palindrome string constructed from these letters .
In the process of construction , Please pay attention to case sensitivity . such as
"Aa"Can't be treated as a palindrome string .Be careful :
Suppose that the length of the string does not exceed 1010.
Example 1
Input :
"abccccdd"
Output :
7
explain :
The longest palindrome string we can construct is "dccaccd", Its length is 7.
Code Java
// Sort Find two similarities - 2ms
public int longestPalindrome(String s) {
int result = 0;
char[] chars = s.toCharArray();
Arrays.sort(chars);
for (int i = 1; i < chars.length; i++) {
if (chars[i] == chars[i-1]) {
i++;
result += 2;
}
}
if (result < chars.length)
return result + 1;
else return result;
}
// Number of hash stores - Less memory usage But it's still slow
public int longestPalindrome1(String s) {
int[] big = new int[26];
int[] small = new int[26];
int result = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= 'a') {
small[ch - 97] ++;
} else {
big[ch - 65] ++;
}
}
for (int i = 0; i < 26; i++) {
result += big[i] / 2 * 2;
result += small[i] / 2 * 2;
}
if (result < s.length())
return result + 1;
else return result;
}
// Optimize array
public int longestPalindrome2(String s) {
int[] count = new int[128];
int length = s.length();
for (int i = 0; i < length; ++i) {
char c = s.charAt(i);
count[c]++;
}
int ans = 0;
for (int v: count) {
ans += v / 2 * 2;
}
if (ans < length)
return ans + 1;
return ans;
}
边栏推荐
- Tongweb customs clearance guidelines
- Celery understands
- 设置自定义dialog的正确宽高
- Some methods of string
- arrayList && linkedList
- Use of mongodb
- Browser screenshot method (long screenshot, node screenshot, designated area screenshot)
- Concurrent programming -- countdownlatch combined with thread pool
- Conf/tongweb Functions of properties
- 移动端适配方案
猜你喜欢
随机推荐
2020 personal annual summary
MySQL basic query
Conf/tongweb Functions of properties
10 signalstartevent and signalcatchingevent of flowable signal events
[automated test] cypress manual
Basic operations of MySQL auto correlation query
OpenGL Mosaic (8)
MySQL transactions and foreign keys
MySQL built-in functions
Timeout thread log for tongweb
19 calling subprocess (callactivity) of a flowable task
移动端适配方案
How to Algorithm Evaluation Methods
Power of leetcode-4 - simple
2021-9-19
Basic application of sentinel series
Hump naming and underlining
Explanation of sentinel series' features, composition and deployment
MySQL performs an inner join on query. The query result is incorrect because the associated fields have different field types.
Cross compile HelloWorld with cmake








