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

相关推荐
sali-tec11 小时前
C# 基于halcon的视觉工作流-章45-网格面划痕
开发语言·算法·计算机视觉·c#
通信小呆呆11 小时前
5G NR 信号检测:从 PSS 相关到 SSB 栅格恢复
算法·5g
Han.miracle11 小时前
数据结构二叉树——层序遍历&& 扩展二叉树的左视图
java·数据结构·算法·leetcode
筱砚.11 小时前
【数据结构——最小生成树与Kruskal】
数据结构·算法
噢,我明白了12 小时前
前端js 常见算法面试题目详解
前端·javascript·算法
怎么没有名字注册了啊13 小时前
查找成绩(数组实现)
c++·算法
沐怡旸13 小时前
【算法】725.分割链表--通俗讲解
算法·面试
L_090714 小时前
【Algorithm】Day-4
c++·算法·leetcode
代码充电宝14 小时前
LeetCode 算法题【简单】20. 有效的括号
java·算法·leetcode·面试·职场和发展
海琴烟Sunshine14 小时前
leetcode 119. 杨辉三角 II python
算法·leetcode·职场和发展