贪心算法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;
    }
相关推荐
smj2302_796826528 小时前
解决leetcode第3943题递增后的数对数量
数据结构·python·算法·leetcode
炽烈小老头9 小时前
【每天学习一点算法 2026/05/25】矩阵中的最长递增路径
学习·算法·矩阵
叁散10 小时前
实验报告:5G 仿真环境与基本链路模拟
算法
从负无穷开始的三次元代码生活10 小时前
算法零碎灵感点分享
算法
染指111010 小时前
9.LangChain框架(实现RAG)
数据库·人工智能·算法·机器学习·ai·大模型
大数据三康11 小时前
在spyder进行的遗传算法练习
开发语言·python·算法
Gene_202211 小时前
轮式底盘的微分平坦
算法
吴佳浩11 小时前
现代多模态大模型的核心基础:Unified Self-Attention
人工智能·算法·llm
小小编程路12 小时前
C++ 常用逻辑运算符
开发语言·c++·算法
Hali_Botebie12 小时前
两种子词分词算法BPE (Byte-Pair Encoding) 和Unigram 区别
人工智能·算法