【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());
    }
}

相关推荐
大熊背20 分钟前
ISP Pipeline中Lv实现方式探究之三--lv计算定点实现
数据结构·算法·自动曝光·lv·isppipeline
西岸行者1 小时前
BF信号是如何多路合一的
算法
大熊背1 小时前
ISP Pipeline中Lv实现方式探究之一
算法·自动白平衡·自动曝光
罗西的思考2 小时前
【OpenClaw】通过 Nanobot 源码学习架构---(5)Context
人工智能·算法·机器学习
Liudef063 小时前
后量子密码学(PQC)深度解析:算法原理、标准进展与软件开发行业的影响
算法·密码学·量子计算
OYpBNTQXi4 小时前
SEAL全同态加密CKKS方案入门详解
算法·机器学习·同态加密
蚂蚁数据AntData4 小时前
破解AI“机器味“困境:HeartBench评测实践详解
大数据·人工智能·算法·机器学习·语言模型·开源
ZC跨境爬虫4 小时前
Python异步IO详解:原理、应用场景与实战指南(高并发爬虫首选)
爬虫·python·算法·自动化
倦王5 小时前
力扣日刷47-补
python·算法·leetcode
沉鱼.445 小时前
第十三届题目
c语言·c++·算法