Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit a1b2458

Browse files
committed
#409 最长回文串 贪心算法
1 parent 2eb248a commit a1b2458

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package greedy;
2+
3+
/**
4+
* @author liangqian0723@gmail.com
5+
* @since 2020/3/19 11:32 PM
6+
*/
7+
public class LC_409_LongestPalindrome {
8+
public int longestPalindrome(String s) {
9+
if (null == s) return 0;
10+
int[] chars = new int[128];
11+
for (char c : s.toCharArray()) {
12+
chars[c]++;
13+
}
14+
int res = 0;
15+
for (int c : chars) {
16+
res += c / 2 * 2;
17+
if (res % 2 == 0 && c % 2 == 1) res++;
18+
}
19+
return res;
20+
}
21+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package greedy;
2+
3+
import org.junit.Test;
4+
5+
import static org.hamcrest.core.Is.is;
6+
import static org.junit.Assert.assertThat;
7+
8+
/**
9+
* @author liangqian0723@gmail.com
10+
* @since 2020/3/19 11:31 PM
11+
*/
12+
public class LC_409_LongestPalindromeTest {
13+
@Test
14+
public void test_longest_palindrome() {
15+
LC_409_LongestPalindrome lp = new LC_409_LongestPalindrome();
16+
assertThat(lp.longestPalindrome("abccccdd"), is(7));
17+
}
18+
}

0 commit comments

Comments
 (0)