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

相关推荐
roman_日积跬步-终至千里3 分钟前
【计算机算法与设计(14)】例题五:最小生成树:Prim算法详细解释:π的含义、更新逻辑和选点原因
算法
让学习成为一种生活方式3 分钟前
压缩文件夹下下所有文件成压缩包tar.gz--随笔016
算法
嗷嗷哦润橘_9 分钟前
AI Agent学习:MetaGPT项目之RAG
人工智能·python·学习·算法·deepseek
不忘不弃27 分钟前
指针元素的使用
算法
he___H29 分钟前
滑动窗口一题
java·数据结构·算法·滑动窗口
AI科技星30 分钟前
统一场论质量定义方程:数学验证与应用分析
开发语言·数据结构·经验分享·线性代数·算法
ULTRA??32 分钟前
KD-Tree的查询原理
python·算法
jianfeng_zhu1 小时前
不带头节点的链式存储实现链栈
数据结构·算法
lightqjx1 小时前
【算法】双指针
c++·算法·leetcode·双指针
历程里程碑1 小时前
C++ 7vector:动态数组的终极指南
java·c语言·开发语言·数据结构·c++·算法