📜  字符的最大和最小 ASCII 值之差恰好为 1 的最长子序列的长度

📅  最后修改于: 2021-10-27 07:47:09             🧑  作者: Mango

给定一个由小写英文字母组成的字符串S ,任务是从给定的字符串找到最长子序列的长度,使得最大和最小ASCII 值之间的差异正好是1

例子:

朴素的方法:解决问题的最简单的方法是生成给定字符串S 的所有可能的子序列,并打印最大长度且最大和最小字符的ASCII 值之差恰好等于的子序列的长度1 .

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

Efficient Approach:优化上述方式,主要思想是使用Map来优化上述方式。请按照以下步骤解决问题:

  • 初始化一个变量,比如maxLength ,它存储结果子序列的最大长度。
  • 将字符的频率存储在 Map 中,比如M
  • 遍历字符串,对于每个字符,比如ch ,检查映射M 中是否存在具有 ASCII 值(ch – 1) 的字符c 。如果发现为真,则将maxLength更新为maxLength(M[ch] + M[ch – 1])的最大值。
  • 完成以上步骤后,打印maxLength的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the maximum length of
// subsequence having difference of ASCII
// value of longest and smallest character as 1
int maximumLengthSubsequence(string str)
{
    // Stores frequency of characters
    unordered_map mp;
 
    // Iterate over characters
    // of the string
    for (char ch : str) {
        mp[ch]++;
    }
    // Stores the resultant
    // length of subsequence
    int ans = 0;
 
    for (char ch : str) {
        // Check if there exists any
        // elements with ASCII value
        // one less than character ch
        if (mp.count(ch - 1)) {
            // Size of current subsequence
 
            int curr_max = mp[ch] + mp[ch - 1];
            // Update the value of ans
            ans = max(ans, curr_max);
        }
    }
 
    // Print the resultant count
    cout << ans;
}
 
// Driver Code
int main()
{
    string S = "acbbebcg";
    maximumLengthSubsequence(S);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the maximum length of
// subsequence having difference of ASCII
// value of longest and smallest character as 1
static void maximumLengthSubsequence(String str)
{
     
    // Stores frequency of characters
    HashMap mp = new HashMap<>();
    for(char ch : str.toCharArray())
    {
        mp.put(ch, mp.getOrDefault(ch, 0) + 1);
    }
     
    // Stores the resultant
    // length of subsequence
    int ans = 0;
 
    for(char ch : str.toCharArray())
    {
         
        // Check if there exists any
        // elements with ASCII value
        // one less than character ch
        if (mp.containsKey((char)(ch - 1)))
        {
             
            // Size of current subsequence
            int curr_max = mp.get(ch) +
                    mp.get((char)(ch - 1));
 
            // Update the value of ans
            ans = Math.max(ans, curr_max);
        }
    }
 
    // Print the resultant count
    System.out.println(ans);
}
 
// Driver Code
public static void main(String[] args)
{
    String S = "acbbebcg";
     
    maximumLengthSubsequence(S);
}
}
 
// This code is contributed by aadityapburujwale


Python3
# Python3 program for the above approach
 
# Function to find the maximum length of
# subsequence having difference of ASCII
# value of longest and smallest character as 1
def maximumLengthSubsequence(str):
     
    # Stores frequency of characters
    mp = {}
 
    # Iterate over characters
    # of the string
    for ch in str:
        if ch in mp.keys():
            mp[ch] += 1
        else:
            mp[ch] = 1
             
    # Stores the resultant
    # length of subsequence
    ans = 0
     
    for ch in str:
         
        # Check if there exists any
        # elements with ASCII value
        # one less than character ch
        if chr(ord(ch) - 1) in mp.keys():
             
            # Size of current subsequence
            curr_max = mp[ch]
             
            if chr(ord(ch) - 1) in mp.keys():
                 curr_max += mp[chr(ord(ch) - 1)]
                  
            # Update the value of ans
            ans = max(ans, curr_max)
 
    # Print the resultant count
    print(ans)
 
# Driver Code
S = "acbbebcg"
 
maximumLengthSubsequence(S)
 
# This code is contributed by Stream_Cipher


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG
{
 
// Function to find the maximum length of
// subsequence having difference of ASCII
// value of longest and smallest character as 1
static void maximumLengthSubsequence(String str)
{
     
    // Stores frequency of characters
    Dictionary mp = new Dictionary();
    foreach(char ch in str.ToCharArray())
    {
        if(mp.ContainsKey(ch))
            mp[ch] = mp[ch] + 1;
        else
            mp.Add(ch, 1);
    }
     
    // Stores the resultant
    // length of subsequence
    int ans = 0;
    foreach(char ch in str.ToCharArray())
    {
         
        // Check if there exists any
        // elements with ASCII value
        // one less than character ch
        if (mp.ContainsKey((char)(ch - 1)))
        {
             
            // Size of current subsequence
            int curr_max = mp[ch] +
                    mp[(char)(ch - 1)];
 
            // Update the value of ans
            ans = Math.Max(ans, curr_max);
        }
    }
 
    // Print the resultant count
    Console.WriteLine(ans);
}
 
// Driver Code
public static void Main(String[] args)
{
    String S = "acbbebcg";  
    maximumLengthSubsequence(S);
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
5

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程