📌  相关文章
📜  一个字符串,该字符串的各字符显示在一个子字符串的最大分区的长度

📅  最后修改于: 2021-05-04 17:45:04             🧑  作者: Mango

给定小写字母的字符串str ,将给定的字符串分成尽可能多的子字符串,以使给定字符串中的每个字符出现在单个子字符串中。任务是打印所有此类分区的长度。

例子:

方法:使用贪婪方法可以轻松解决此问题。请按照以下步骤解决问题。

  1. 将所有字符的最后一个索引存储在字符串
  2. 由于字符串仅包含小写字母,因此只需使用固定大小为26的数组来存储每个字符的最后一个索引。
  3. 遍历给定的字符串,然后执行以下步骤:
    • 当前字符添加到该分区如果字符的最后一个位置超过了当前的指数和增加分区的长度。
    • 如果当前字符的最后一个索引等于当前索引,则存储其长度并继续到下一个字符,依此类推。
  4. 完成上述步骤后,打印所有存储的长度。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the length of
// all partitions oof a string such
// that each characters occurs in
// a single substring
void partitionString(string s)
{
    int n = s.size();
 
    // Stores last index of string s
    vector ans;
 
    if (n == 0) {
        cout << "-1";
        return;
    }
 
    // Find the last position of
    // each letter in the string
    vector last_pos(26, -1);
 
    for (int i = n - 1; i >= 0; --i) {
 
        // Update the last index
        if (last_pos[s[i] - 'a'] == -1) {
            last_pos[s[i] - 'a'] = i;
        }
    }
 
    int minp = -1, plen = 0;
 
    // Iterate the given string
    for (int i = 0; i < n; ++i) {
 
        // Get the last index of s[i]
        int lp = last_pos[s[i] - 'a'];
 
        // Extend the current partition
        // characters last pos
        minp = max(minp, lp);
 
        // Increase len of partition
        ++plen;
 
        // if the current pos of
        // character equals the min pos
        // then the end of partition
        if (i == minp) {
 
            // Store the length
            ans.push_back(plen);
            minp = -1;
            plen = 0;
        }
    }
 
    // Print all the partition lengths
    for (int i = 0;
         i < (int)ans.size(); i++) {
        cout << ans[i] << " ";
    }
}
 
// Driver Code
int main()
{
    // Given string str
    string str = "acbbcc";
 
    // Function Call
    partitionString(str);
 
    return 0;
}


Java
// Java program for
// the above approach
import java.util.*;
class GFG{
 
// Function to find the length of
// all partitions oof a String such
// that each characters occurs in
// a single subString
static void partitionString(String s)
{
  int n = s.length();
 
  // Stores last index of String s
  Vector ans =
         new Vector();
 
  if (n == 0)
  {
    System.out.print("-1");
    return;
  }
 
  // Find the last position of
  // each letter in the String
  int []last_pos = new int[26];
  Arrays.fill(last_pos, -1);
 
  for (int i = n - 1; i >= 0; --i)
  {
    // Update the last index
    if (last_pos[s.charAt(i) - 'a'] == -1)
    {
      last_pos[s.charAt(i) - 'a'] = i;
    }
  }
 
  int minp = -1, plen = 0;
 
  // Iterate the given String
  for (int i = 0; i < n; ++i)
  {
    // Get the last index of s[i]
    int lp = last_pos[s.charAt(i) - 'a'];
 
    // Extend the current partition
    // characters last pos
    minp = Math.max(minp, lp);
 
    // Increase len of partition
    ++plen;
 
    // if the current pos of
    // character equals the min pos
    // then the end of partition
    if (i == minp)
    {
      // Store the length
      ans.add(plen);
      minp = -1;
      plen = 0;
    }
  }
 
  // Print all the partition lengths
  for (int i = 0; i < (int)ans.size(); i++)
  {
    System.out.print(ans.get(i) + " ");
  }
}
 
// Driver Code
public static void main(String[] args)
{
  // Given String str
  String str = "acbbcc";
 
  // Function Call
  partitionString(str);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program for the above approach
 
# Function to find the length of
# all partitions oof a string such
# that each characters occurs in
# a single substring
def partitionString(s):
     
    n = len(s)
 
    # Stores last index of string s
    ans = []
 
    if (n == 0):
        print("-1")
        return
     
    # Find the last position of
    # each letter in the string
    last_pos = [-1] * 26
 
    for i in range(n - 1 , -1 , -1):
 
        # Update the last index
        if (last_pos[ord(s[i]) - ord('a')] == -1):
            last_pos[ord(s[i]) - ord('a')] = i
     
    minp = -1
    plen = 0
 
    # Iterate the given string
    for i in range(n):
 
        # Get the last index of s[i]
        lp = last_pos[ord(s[i]) - ord('a')]
 
        # Extend the current partition
        # characters last pos
        minp = max(minp, lp)
 
        # Increase len of partition
        plen += 1
 
        # if the current pos of
        # character equals the min pos
        # then the end of partition
        if (i == minp):
 
            # Store the length
            ans.append(plen)
            minp = -1
            plen = 0
         
    # Print all the partition lengths
    for i in range(len(ans)):
        print(ans[i], end = " ")
 
# Driver Code
 
# Given string str
str = "acbbcc"
 
# Function call
partitionString(str)
 
# This code is contributed by code_hunt


C#
// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find the length of
// all partitions oof a String such
// that each characters occurs in
// a single subString
static void partitionString(String s)
{
  int n = s.Length;
 
  // Stores last index of String s
  List ans = new List();
 
  if (n == 0)
  {
    Console.Write("-1");
    return;
  }
 
  // Find the last position of
  // each letter in the String
  int []last_pos = new int[26];
  for (int i = 0; i < 26; ++i)
  {
    last_pos[i] = -1; 
  }
 
  for (int i = n - 1; i >= 0; --i)
  {
    // Update the last index
    if (last_pos[s[i] - 'a'] == -1)
    {
      last_pos[s[i] - 'a'] = i;
    }
  }
 
  int minp = -1, plen = 0;
 
  // Iterate the given String
  for (int i = 0; i < n; ++i)
  {
    // Get the last index of s[i]
    int lp = last_pos[s[i] - 'a'];
 
    // Extend the current partition
    // characters last pos
    minp = Math.Max(minp, lp);
 
    // Increase len of partition
    ++plen;
 
    // if the current pos of
    // character equals the min pos
    // then the end of partition
    if (i == minp)
    {
      // Store the length
      ans.Add(plen);
      minp = -1;
      plen = 0;
    }
  }
 
  // Print all the partition lengths
  for (int i = 0; i < (int)ans.Count; i++)
  {
    Console.Write(ans[i] + " ");
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given String str
  String str = "acbbcc";
 
  // Function Call
  partitionString(str);
}
}
 
// This code is contributed by Rajput-Ji


输出:
1 5





时间复杂度: O(N)
辅助空间: O(N)