Stay button --- 2020.3.19

409. The longest palindrome string

//贪心算法
class Solution {
    public int longestPalindrome(String s) {
        int[] count = new int[58];
        for (char c: s.toCharArray())
            count[c-'A']++;

        int ans = 0;
        for (int v: count) {
            ans += v / 2 * 2;
            if (v % 2 == 1 && ans % 2 == 0)
                ans++;
        }
        return ans;
    }
}
//int数组计数
class Solution {
    public int longestPalindrome(String s) {
      int[] cnt = new int[58];
      for (char c : s.toCharArray()) {
        cnt[c - 'A'] += 1;
      }

      int ans = 0;
      for (int x: cnt) {
        // 字符出现的次数最多用偶数次。
        ans += x - (x & 1);
      }
      // 如果最终的长度小于原字符串的长度,说明里面某个字符出现了奇数次,那么那个字符可以放在回文串的中间,所以额外再加一。
      return ans < s.length() ? ans + 1 : ans;  
    }
}

05. replace spaces face questions

class Solution {
    public String replaceSpace(String s) {
        return s.replace(" ", "%20");
    }
}
class Solution {
    public String replaceSpace(String s) {
        StringBuilder res = new StringBuilder();
        //Character是char的包装类
        for(Character c : s.toCharArray())
        {
            if(c == ' ') res.append("%20");
            else res.append(c);
        }
        return res.toString();
    }
}

24. The inversion face questions list

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode nextTemp = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return nextTemp;
    }
}
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null,curr = head,next = null;
        while(curr != null){
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
}

The more you know, the more you do not know.
Proper way without surgery, patients can still seek, there is no way to surgery, ending surgery.
If you have other questions, welcome message, we can discuss, learn together and progress together

He published 193 original articles · won praise 116 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_40722827/article/details/104976417