Skip to main content

Command Palette

Search for a command to run...

LeetCode Solution, Medium, 763. Partition Labels

Published

I am not a programmer just a leaner. Writing JavaScript, Python, and Go and doing something on Kubernetes.

763. Partition Labels

題目敘述

You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.

Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.

Return a list of integers representing the size of these parts.

Example 1:

Input: s = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits s into less parts.

Example 2:

Input: s = "eccbbbbdec"
Output: [10]

Constraints:

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.

Hint 1:

Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.

題目翻譯

必須說這題的敘述真的是有夠不明確的,看一下別人的討論才終於比較懂說要幹嘛。題目給定一個字串s,想要將其盡可能的拆分。但是有一個條件,就是同一個字母需要在同一個部分。表示說,今天有個字串s"acbacdefe",就只能拆成"acbac""defe"。因為一開始的a,所以要找到下一個a,但是第二個字母e之後又比最後一個a更後面。

解法解析

用一個 hash map 紀錄每個字母的最後出現的 index,然後去迭代 s 的所有值。使用anchor紀錄最開頭的值。 當 i相等於j(該字母最後出現的index值),代表找到了拆分的地方,就將其長度(i-anchor)記錄到ans

解法範例

Go

func partitionLabels(s string) []int {
    last := make(map[rune]int)
    for i, c := range s {
        last[c] = i
    }

    var anchor int = -1
    var j int
    var ans []int

    for i, c := range s {
        if last[c] > j {
            j = last[c]
        }

        if i == j {
            ans = append(ans, i-anchor)
            anchor = i
        }
    }
    return ans
}

JavaScript

/**
 * @param {string} s
 * @return {number[]}
 */
var partitionLabels = function (s) {
    const last = {};
    for (let i = 0; i < s.length; i++) {
        last[s[i]] = i;
    }
    let j = 0,
        anchor = -1;
    const ans = [];
    for (let i = 0; i < s.length; i++) {
        j = Math.max(j, last[s[i]]);
        if (i === j) {
            ans.push(i - anchor);
            anchor = i;
        }
    }
    return ans;
};

Kotlin

class Solution {
    fun partitionLabels(s: String): List<Int> {
        val ans = mutableListOf<Int>()

        val last = IntArray(26)
        for ((i, c) in s.withIndex()) {
            last[c - 'a'] = i
        }

        var anchor = 0
        var j = last[s[0] - 'a']
        for (i in s.indices) {
            j = maxOf(j, last[s[i] - 'a'])

            if (i == j) {
                ans.add(j - anchor + 1)
                anchor = j + 1
            }
        }

        return ans
    }
}

PHP

class Solution
{

    /**
     * @param String $s
     * @return Integer[]
     */
    function partitionLabels($s)
    {
        $len = strlen($s);
        $last = [];
        $ans = [];
        for ($i = 0; $i < $len; $i++) {
            $last[$s[$i]] = $i;
        }
        $anchor = -1;
        $j = 0;
        for ($i = 0; $i < $len; $i++) {
            $j = max($j, $last[$s[$i]]);
            if ($i == $j) {
                array_push($ans, $j - $anchor);
                $anchor = $j;
            }
        }
        return $ans;
    }
}

Python

class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        last = {c: i for i, c in enumerate(s)}
        j = 0
        anchor = -1
        ans = []
        for i, c in enumerate(s):
            j = max(j, last[c])
            if i == j:
                ans.append(i - anchor)
                anchor = i

        return ans

Rust

use std::collections::HashMap;

impl Solution {
    pub fn partition_labels(s: String) -> Vec<i32> {
        let mut ans = Vec::<i32>::new();
        let mut last = HashMap::<char,_>::new();
        for (i, c) in s.chars().enumerate() {
            last.insert(c, i);
        }
        let mut anchor = 0;
        let mut j = 0;
        for( i, c) in s.chars().enumerate() {
            j = j.max(*last.get(&c).unwrap());
            if i == j {
                ans.push((j - anchor + 1) as i32);
                anchor = j + 1;
            }
        }
        ans
    }
}

Swift

class Solution {
    func partitionLabels(_ s: String) -> [Int] {
        var last = [Character:Int]()
        for (i, c) in s.enumerated() {
            last[c, default: 0] = i
        }

        var ans = [Int]()
        var j = 0
        var anchor = -1
        for (i, c) in s.enumerated() {
            j = max(j, last[c, default: 0])
            if i == j {
                ans.append(i - anchor)
                anchor = i
            }
        }
        return ans
    }
}

LeetCode Solution

Part 1 of 50

A collection of leetcode solustion

More from this blog

如何開始入門軟體工程領域 - 名詞解釋(長期更新)

現在應該開始有很多人想要踏入軟體工程的領域,但在進入這個領域之前,覺得先了解一些名詞,可以在入門時更有方向也更知道要用什麼關鍵字去找尋有用的資訊。這篇文章就是想要幫助想要入門的人理解一些軟體工程裡的專有名詞。 作業系統 這一區塊主要解釋跟作業系統層面相關的名詞 英文中文解釋 Operation system 簡稱 OS | 作業系統 | 就是電腦的作業系統,是三大作業系統分別是:Linux、Windows、macOS | | Linux | | 自由和開放原始碼的 UNI...

May 10, 2023

我的 MacBook Pro (Apple Silicon) 設定

現在開始因為 ChatGPT 的出現,各種 AI 助手的功能都跑出來了。想想自己用了許久的環境設定也應該要來重新審視和建立新的開發環境了,僅此紀錄我個人的環境配置步驟和設定。 環境前置步驟 還原 MacBook Pro 至全新環境 macOS(全部資料刪除) 設定好初始設定後,登入 Apple ID 進入 App Store 確定 macOS 版本和預設 APP 都更新到最新 macOS 版本 到系統設定調整所有設定至個人習慣的設定 三指拖移 觸控板手勢開啟 防火牆開啟 輸入法設定...

Apr 25, 2023

ChatGPT 下的發展預想

從 ChatGPT 問世到現在,有許許多多的文章和討論出來。先從最早的 Google 要完蛋了,到後來的工作要被取代了,工程師失業了。 我就比較沒有想要馬上出來評論一下,我喜歡讓子彈飛一會兒。跟討論一下我自己比較在意的討論點。 Google 為什麼慢了? 結論:因為他需要更小心 很多人說 Google 怎麼被微軟搶先了一步。剛開始 Bing 說要加上 AI 的時候大家都在說 Google 怎麼慢了。我就馬上跑去看 OpenAI 的網站,靠北呀啊就 Azure 贊助的。那當然在正式上線 ChatG...

Mar 23, 2023

不工程的攻城獅

223 posts

I am not a programmer because I am not good at programming. But I do programming. Love to learn new things. An animal lover and a dancer. My oshi is 潤羽るしあ.