贪心算法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;
    }
相关推荐
gihigo19981 天前
matlab 基于瑞利衰落信道的误码率分析
算法
foxsen_xia1 天前
go(基础06)——结构体取代类
开发语言·算法·golang
foxsen_xia1 天前
go(基础08)——多态
算法·golang
leoufung1 天前
用三色 DFS 拿下 Course Schedule(LeetCode 207)
算法·leetcode·深度优先
im_AMBER1 天前
算法笔记 18 二分查找
数据结构·笔记·学习·算法
C雨后彩虹1 天前
机器人活动区域
java·数据结构·算法·华为·面试
MarkHD1 天前
车辆TBOX科普 第53次 三位一体智能车辆监控:电子围栏算法、驾驶行为分析与故障诊断逻辑深度解析
算法
苏小瀚1 天前
[算法]---路径问题
数据结构·算法·leetcode
月明长歌1 天前
【码道初阶】一道经典简单题:多数元素(LeetCode 169)|Boyer-Moore 投票算法详解
算法·leetcode·职场和发展
wadesir1 天前
C语言模块化设计入门指南(从零开始构建清晰可维护的C程序)
c语言·开发语言·算法