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

相关推荐
老鼠只爱大米2 分钟前
LeetCode经典算法面试题 #78:子集(回溯法、迭代法、动态规划等多种实现方案详细解析)
算法·leetcode·动态规划·回溯·位运算·子集
执着2596 分钟前
力扣hot100 - 199、二叉树的右视图
数据结构·算法·leetcode
I_LPL10 分钟前
day21 代码随想录算法训练营 二叉树专题8
算法·二叉树·递归
可编程芯片开发17 分钟前
基于PSO粒子群优化PI控制器的无刷直流电机最优控制系统simulink建模与仿真
人工智能·算法·simulink·pso·pi控制器·pso-pi
cpp_250117 分钟前
P8448 [LSOT-1] 暴龙的土豆
数据结构·c++·算法·题解·洛谷
YGGP18 分钟前
【Golang】LeetCode 49. 字母异位词分组
leetcode
lcj251118 分钟前
深入理解指针(4):qsort 函数 & 通过冒泡排序实现
c语言·数据结构·算法
fie888920 分钟前
基于MATLAB的转子动力学建模与仿真实现(含碰摩、不平衡激励)
开发语言·算法·matlab
唐梓航-求职中26 分钟前
编程大师-技术-算法-leetcode-1472. 设计浏览器历史记录
算法·leetcode
_OP_CHEN29 分钟前
【算法基础篇】(五十八)线性代数之高斯消元法从原理到实战:手撕模板 + 洛谷真题全解
线性代数·算法·蓝桥杯·c/c++·线性方程组·acm/icpc·高斯消元法