力扣---2020.3.19

409. 最长回文串

//贪心算法
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. 替换空格

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. 反转链表

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;
    }
}

你知道的越多,你不知道的越多。
有道无术,术尚可求,有术无道,止于术。
如有其它问题,欢迎大家留言,我们一起讨论,一起学习,一起进步

发布了193 篇原创文章 · 获赞 116 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40722827/article/details/104976417
今日推荐