贪心算法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;
    }
相关推荐
diediedei4 分钟前
C++中的适配器模式变体
开发语言·c++·算法
Timmylyx05187 分钟前
Codeforces Round 1075 (Div. 2) 题解
算法·codeforces·比赛日记
hadage23315 分钟前
--- 力扣oj柱状图中最大的矩形 单调栈 ---
算法·leetcode·职场和发展
json{shen:"jing"}16 分钟前
18. 四数之和
数据结构·算法·leetcode
千逐-沐风16 分钟前
SMU-ACM2026冬训周报1st
算法
天赐学c语言17 分钟前
1.25 - 零钱兑换 && 理解右值以及move的作用
c++·算法·leecode
北冥湖畔的燕雀19 分钟前
C++智能指针:告别内存泄漏的利器
c++·算法
傻乐u兔23 分钟前
C语言进阶————数据在内存中的存储1
c语言·数据结构·算法
多米Domi01139 分钟前
0x3f 第42天 复习 10:39-11:33
算法·leetcode
thubier(段新建)41 分钟前
单招模考试卷模型思考(1)
算法·单招