409.求最长回文串的长度 LongestPalindrome

题目要求求出长度即可,并不需要求出最长回文串。
思路:用字典统计每一个字符的出现次数,出现次数大于1的字符必定出现在回文串中,另外还再加上一个中心点。
  1. public static int LongestPalindrome(string s) {
  2. int length = 0;
  3. Dictionary<char, int> dictionary = new Dictionary<char, int>();
  4. int value = 0;
  5. foreach (char c in s) {
  6. if (dictionary.TryGetValue(c, out value)) {
  7. dictionary[c]+=1;
  8. } else {
  9. dictionary[c] = 1;
  10. }
  11. }
  12. bool addCenter = false;
  13. foreach (int val in dictionary.Values) {
  14. if (addCenter == false && val % 2 != 0) {
  15. length++;
  16. addCenter = true;
  17. }
  18. if (val > 1) {
  19. length += (val - val % 2);
  20. }
  21. }
  22. return length;
  23. }





posted @ 2017-01-10 23:18  xiejunzhao  阅读(113)  评论(0编辑  收藏  举报