Post-Amazon Era LeetCode 日记

189 阅读1分钟

——————————————————————————————————————————————————————————————

            #################################
                    Num so far : 2
            #################################

——————————————————————————————————————————————————————————————

  1. Trapping Rain Water

    class Solution { public int trap(int[] height) { if(height.length <= 2) return 0; int ans = 0, lmax = 0, rmax = 0, l = 0, r = height.length - 1; while(l < r){ if(height[l] < height[r]){ if(height[l] > lmax) lmax = height[l++]; else ans += lmax - height[l++]; } else{ if(height[r] > rmax) rmax = height[r--]; else ans += rmax - height[r--]; } }

    return ans;
    

    } }

  2. Longest Palindrome

one slow solution:

class Solution {
public int longestPalindrome(String s) {
    if(s == null || s.length() == 0) return 0;
    Map<Character, Integer> hm = new HashMap<>();
    int n = s.length(), center = 0, ans = 0;
    for(int i = 0; i < n; i++){
        char c = s.charAt(i);
        hm.put(c, hm.getOrDefault(c, 0) + 1);
    } 
    for(int i = 0; i < n; i++){
        char c = s.charAt(i);
        if(hm.get(c) % 2 == 0){
            ans += hm.get(c);
            hm.put(c, 0);
        }
        else if(hm.get(c) > 1){
            ans += hm.get(c) - 1;
            if(center == 0){
                center = 1;
                hm.put(c, 0);
            }
            else hm.put(c, 1);
        }
        else if(hm.get(c) == 1){
            if(center == 0){
                center = 1;
                hm.put(c, 0);
            }
        }
    }
    return ans + center;
    
}
}
//
class Solution {
public int longestPalindrome(String s) {
    if(s == null || s.length() == 0) return 0;
    int[] times = new int[128];
    int ans = 0;
    for(char c : s.toCharArray()){
        times[c - '0']++;
    }
    for(int v:times){
        ans += v / 2 * 2;
        if(ans % 2 == 0 && v % 2 == 1) ans++;
    }
    return ans;
    
}
}