【Hot100】LeetCode—763. 划分字母区间

目录

  • 题目
  • [1- 思路](#1- 思路)
  • [2- 实现](#2- 实现)
    • [⭐763. 划分字母区间------题解思路](#⭐763. 划分字母区间——题解思路)
  • [3- ACM 实现](#3- ACM 实现)

题目


1- 思路

思路

目标:同样的字母 字符串尽可能的长

  • 问1:怎么确定字母数 ------> 哈希表
  • 问2:怎么让字符尽可能的长?------> 统计每个字符出现的最远位置 ,根据单个字符的最远出现位置,判断字符串的最远出现位置
    • 如果满足 字符串中所有字符的最远出现位置 <= 当前字符串的最远出现位置,这个字符串就是最长的

2- 实现

⭐763. 划分字母区间------题解思路

java 复制代码
class Solution {
    
    List<Integer> res = new ArrayList<>();
    public List<Integer> partitionLabels(String s) {
        // 1.定义 hash
        int[] hash = new int[26];
        // 2. 求单个字母最远距离
        for(int i = 0 ; i < s.length();i++){
            hash[s.charAt(i) - 'a'] = i;
        }

        int left = 0;
        int right = 0;
        // 3. 实现逻辑
        for(int i = 0 ; i < s.length();i++){
            right = Math.max(right,hash[s.charAt(i)-'a']);
            if(i==right){
                res.add(right-left+1);
                left = right+1;
            }
        }
        return res;
    }
}

3- ACM 实现

java 复制代码
public class longestSub {

    static List<Integer> res = new ArrayList<>();
    public static List<Integer> partitionLabels(String str){
        // 1. 定义 hash
        int len = str.length();
        int[] hash = new int[len];
        // 2. 求单个字符最远
        for(int i = 0 ; i < len;i++){
            hash[str.charAt(i)-'a'] = i;
        }

        int left = 0;
        int right = 0;
        // 3. 实现逻辑
        for(int i = 0 ; i < len;i++){
            right = Math.max(right,hash[str.charAt(i)-'a']);

            if(i==right){
                res.add(right-left+1);
                left = right+1;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        List<Integer> forRes = partitionLabels(str);
        System.out.println(forRes.toString());
    }
}

相关推荐
啊嘞嘞?33 分钟前
力扣(滑动窗口最大值)
算法·leetcode·职场和发展
快递鸟33 分钟前
ISV系统开发中物流接口的第三方模块对接:技术选型与集成实践
算法
墨染点香34 分钟前
LeetCode 刷题【53. 最大子数组和】
数据结构·算法·leetcode
2501_924879261 小时前
客流特征识别误报率↓76%!陌讯多模态时序融合算法在智慧零售的实战解析
大数据·人工智能·算法·目标检测·计算机视觉·视觉检测·零售
北京地铁1号线1 小时前
广告推荐模型2:因子分解机(Factorization Machines, FM)
人工智能·算法·推荐算法
七十二小時2 小时前
力扣热题——前K个高频元素
数据结构·算法·leetcode
500佰2 小时前
AI手办,Gemini 2.5 Flash Image 可一键制作高一致性人物手办
算法
愚润求学3 小时前
【贪心算法】day3
c++·算法·leetcode·贪心算法
空白到白4 小时前
算法练习-合并两个有序数组
数据结构·python·算法
YuTaoShao4 小时前
【LeetCode 热题 100】75. 颜色分类——双指针
算法·leetcode·职场和发展