贪心算法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;
    }
相关推荐
呆呆的小鳄鱼19 分钟前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香19 分钟前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely20 分钟前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_071220 分钟前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_36 分钟前
cf1925B&C
数据结构·算法
YuTaoShao1 小时前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先
Wendy14419 小时前
【线性回归(最小二乘法MSE)】——机器学习
算法·机器学习·线性回归
拾光拾趣录9 小时前
括号生成算法
前端·算法
渣呵9 小时前
求不重叠区间总和最大值
算法
拾光拾趣录10 小时前
链表合并:双指针与递归
前端·javascript·算法