--- greedy strategy to make the same kind of character-delimited string appear together

Delimited string to make the same kind of characters appear together

763. Partition Labels (Medium)

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.

Subject description:

  This question gives us a string s, which is then divided into as many sub-strings, each character that can appear in a maximum of a substring, the difficulty of solving the problem is to find the string breakpoints, that split position of the substring, the title of example that we look closely, you may find that once there was a letter several times, then the position must be the last to appear in the current sub-string, the letters a, e and j substrings are three letters end. So our concern is the location of the last occurrence of each letter, we can use the map to save each letter and location of its last occurrence.

  After you create a map, we traverse the string s, we maintain a start variable, is currently the starting position of the substring, there is a last variable is the end of the current position of the substring, whenever we traverse to the letter, we a map extracted from the last position in which it appears, as soon as a string containing a letter, the letter should contain all the same, so we have to keep the last update with the last variable current letter subscript, only when i and equal to the last time, it is the current place of the substring disconnected.

Code:

class Solution {
    public List<Integer> partitionLabels(String S) {
        List<Integer>res=new ArrayList<>();
    if(S==null||S.length()==0)
        return res;
    int []map=new int [26]; //记录每个字母出现的最后一个下标
    for(int i=0;i<S.length();i++){
        map[S.charAt(i)-'a']=i;
    }
    int start=0;
    int last=0;
    while(start<S.length()){
        int i=start;
        while(i<S.length()){
        last=Math.max(last,map[S.charAt(i)-'a']);//取访问到的字母的最大最后一个坐标更新last
        if(last==i){
            res.add(i-start+1);
            start=i+1;
            break;
        }
            i++;
        }
    }
    return res;
    }
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11106039.html
Recommended