贪心算法day 06

1.最长回文串

链接:. - 力扣(LeetCode)

思路:计算每个字符个数如果是偶数个那么肯定可以组成回文串,如果是奇数个就会有一个无法组成回文串,但是在最中间还是可以有一个不是成队的字符这个字符就从多的奇数中随机取一个就好。这里使用模拟hash的方式来实现每个字符的计数。

代码:

复制代码
 public static int longestPalindrome1(String s) {
        int n = s.length();
        int[] hash = new int[127];
        //如何将字符串转化成字符串数组? 如何统计每个字符串的对应个数
        for (int i = 0; i < n; i++) {
            hash[s.charAt(i)]++;
        }
        int ret = 0;
        for(int x:hash){
            ret += x / 2 * 2;
        }
        return ret < s.length() ? ret + 1 : ret ;
    } 

2.增减字符串匹配

链接:. - 力扣(LeetCode)

思路: 代码:

复制代码
class Solution {
     public static int[] diStringMatch(String s) {
          int n = s.length();
          int left = 0,right = n;
          int[] ret = new int[n + 1];
        for (int i = 0; i < n; i++) {
            ret[i] = i;
        }

        for (int i = 0; i < n; i++) {
            if(s.charAt(i) == 'I' ){
                ret[i] = left++;
            }else{
                ret[i] = right--;
            }
            
        }
        ret[n] = left;
        return ret;
    }
}

3.分发饼干

题目链接:. - 力扣(LeetCode)

解题思路:与田径赛马差不多的思路

代码:

复制代码
  public static int findContentChildren(int[] g, int[] s) {
        Arrays.sort(g);//胃口大小
        Arrays.sort(s);//饼干尺寸
        int m = g.length, n = s.length,ret = 0;
          // 两个指针同时遍历不是分开两层遍历
      for(int i = 0,j = 0;i < m && j < n ; i++,j++){
          while(j < n && s[j] < g[i])j++;
          if(j < n) ret++;
      }
          return ret;
    }
相关推荐
DuHz13 分钟前
基于频率分集阵列的MIMO雷达联合距离角度估计——论文阅读
论文阅读·算法·汽车·信息与通信·毫米波雷达
INGNIGHT34 分钟前
单词搜索 II · Word Search II
数据结构·c++·算法
黄卷青灯771 小时前
标定系数为什么会存储在相机模组里面,在标定的时候,算法是在割草机的X3板上运行的啊?
数码相机·算法·相机内参
螺丝钉的扭矩一瞬间产生高能蛋白1 小时前
PID算法基础知识
算法
HVACoder2 小时前
复习下线性代数,使用向量平移拼接两段线
c++·线性代数·算法
爱coding的橙子2 小时前
每日算法刷题Day77:10.22:leetcode 二叉树bfs18道题,用时3h
算法·leetcode·职场和发展
Swift社区2 小时前
LeetCode 404:左叶子之和(Sum of Left Leaves)
算法·leetcode·职场和发展
南枝异客2 小时前
查找算法-顺序查找
python·算法
QuantumLeap丶2 小时前
《数据结构:从0到1》-06-单链表&双链表
数据结构·算法
李牧九丶3 小时前
从零学算法59
算法