📌  相关文章
📜  检查是否存在只有 2 个不同字符的 K 长度子字符串,每个字符的频率大于 K/3

📅  最后修改于: 2022-05-13 01:57:07.641000             🧑  作者: Mango

检查是否存在只有 2 个不同字符的 K 长度子字符串,每个字符的频率大于 K/3

给定一个由小写字母组成的字符串S和一个整数K ,任务是查找是否存在长度为K且只有 2 个唯一字符的子字符串,并且这两个字符的计数必须大于K /3 。如果存在这样的字符串,则打印“ YES ”,否则打印“ NO ”。

例子:

方法:该任务可以通过使用滑动窗口技术检查所有K长度子字符串来解决,方法是跟踪当前子字符串中唯一字符的数量。请按照以下步骤解决问题:

  • 取一个无序映射来存储当前子字符串中的字符数及其频率,如果
    • 当前子字符串中只有 2 个不同的字符,并且
    • 没有一个字符的计数小于或等于K/3
  • 当前子字符串是有效字符串。
  • 因此打印YES ,
  • 如果没有遇到有效的子字符串,则打印NO

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check whether
// a valid substring exists or not
void checkGoldenString(string S, int k)
{
    // Store the count of distinct chars
    // with their frequencies
    unordered_map occ;
 
    int n = S.length();
 
    // First substring of length k
    for (int i = 0; i < k; i++)
        occ[S[i]]++;
 
    // Check if it is valid
    if (occ.size() == 2) {
        int x = -1, y = -1;
        for (auto item : occ) {
            if (x == -1)
                x = item.second;
            else
                y = item.second;
        }
 
        // Count of one of the chars is
        // greater than k/3
        if (x >= k / 3 && y >= k / 3) {
            cout << "YES\n";
            return;
        }
    }
 
    // Sliding over the entire string
    for (int i = k; i < n; i++) {
 
        // Discarding first character of
        // previous window
        occ[S[i - k]]--;
 
        // Erase it from the map, if its
        // frequency becomes 0
        if (occ[S[i - k]] == 0)
            occ.erase(S[i - k]);
 
        // Increment count of current char
        occ[S[i]]++;
 
        // Checking valid or not
        if (occ.size() == 2) {
            int x = -1, y = -1;
            for (auto item : occ) {
                if (x == -1)
                    x = item.second;
                else
                    y = item.second;
            }
 
            if (x >= k / 3 && y >= k / 3) {
                cout << "YES\n";
                return;
            }
        }
    }
 
    // No valid substring is found
    cout << "NO\n";
}
 
// Driver Code
int main()
{
    int K = 6;
    string S = "abaaaa";
    checkGoldenString(S, K);
 
    K = 4;
    S = "abbaaaa";
    checkGoldenString(S, K);
}


Java
// Java program for the above approach
import java.util.HashMap;
class GFG {
 
    // Function to check whether
    // a valid substring exists or not
    public static void checkGoldenString(String S, int k)
    {
       
        // Store the count of distinct chars
        // with their frequencies
        HashMap occ = new HashMap();
 
        int n = S.length();
 
        // First substring of length k
        for (int i = 0; i < k; i++) {
            if (occ.containsKey(S.charAt(i))) {
                occ.put(S.charAt(i), occ.get(S.charAt(i)) + 1);
            } else {
                occ.put(S.charAt(i), 1);
            }
        }
 
        // Check if it is valid
        if (occ.size() == 2) {
            int x = -1, y = -1;
            for (char item : occ.keySet()) {
                if (x == -1)
                    x = occ.get(item);
                else
                    y = occ.get(item);
            }
 
            // Count of one of the chars is
            // greater than k/3
            if (x >= k / 3 && y >= k / 3) {
                System.out.println("YES");
                return;
            }
        }
 
        // Sliding over the entire string
        for (int i = k; i < n; i++) {
 
            // Discarding first character of
            // previous window
            occ.put(S.charAt(i - k), occ.get(S.charAt(i - k)) - 1);
 
            // Erase it from the map, if its
            // frequency becomes 0
            if (occ.get(S.charAt(i - k)) == 0)
                occ.remove(S.charAt(i - k));
 
            // Increment count of current char
            if (occ.containsKey(S.charAt(i))) {
                occ.put(S.charAt(i), occ.get(S.charAt(i)) + 1);
            } else {
                occ.put(S.charAt(i), 1);
            }
 
            // Checking valid or not
            if (occ.size() == 2) {
                int x = -1, y = -1;
                for (char item : occ.keySet()) {
                    if (x == -1)
                        x = occ.get(item);
                    else
                        y = occ.get(item);
                }
 
                if (x >= k / 3 && y >= k / 3) {
                    System.out.println("YES");
                    return;
                }
            }
        }
 
        // No valid substring is found
        System.out.println("NO");
    }
 
    // Driver Code
    public static void main(String args[]) {
        int K = 6;
        String S = "abaaaa";
        checkGoldenString(S, K);
 
        K = 4;
        S = "abbaaaa";
        checkGoldenString(S, K);
    }
}
 
// This code is contributed by saurabh_jaiswal.


Python3
# Python Program to implement
# the above approach
 
# Function to check whether
# a valid substring exists or not
def checkGoldenString(S, k):
 
    # Store the count of distinct chars
    # with their frequencies
    occ = dict()
 
    n = len(S)
 
    # First substring of length k
    for i in range(k):
        if (S[i] not in occ):
            occ[S[i]] = 1
        else:
            occ[S[i]] += 1
 
    # Check if it is valid
    if (len(occ) == 2):
        x = -1
        y = -1
        for z in occ.values():
            if (x == -1):
                x = z
            else:
                y = z
 
        # Count of one of the chars is
        # greater than k/3
        if (x >= k // 3 and y >= k // 3):
            print("YES")
            return
 
    # Sliding over the entire string
    for i in range(k, n):
 
        # Discarding first character of
        # previous window
        if (S[i - k] in occ):
            occ[[S[i - k]]] -= k
 
        # Erase it from the map, if its
        # frequency becomes 0
        if (occ[S[i - k]] == 0):
            del occ[S[i - k]]
 
        # Increment count of current char
        if (S[i] not in occ):
            occ[S[i]] = 1
        else:
            occ[S[i]] += 1
 
        # Checking valid or not
        if (len(occ) == 2):
            x = -1
            y = -1
            for z in occ.values:
                if (x == -1):
                    x = z
                else:
                    y = z
 
            if (x >= k // 3 and y >= k // 3):
                print("YES" + '
')                 return       # No valid substring is found     print("NO")   # Driver Code K = 6 S = "abaaaa" checkGoldenString(S, K)   K = 4 S = "abbaaaa" checkGoldenString(S, K)   # This code is contributed by Saurabh Jaiswal


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG {
 
    // Function to check whether
    // a valid substring exists or not
    public static void checkGoldenString(String S, int k)
    {
       
        // Store the count of distinct chars
        // with their frequencies
        Dictionary occ = new Dictionary();
 
        int n = S.Length;
 
        // First substring of length k
        for (int i = 0; i < k; i++) {
            if (occ.ContainsKey(S[i])) {
                occ[S[i]] = occ[S[i]] + 1;
            } else {
                occ.Add(S[i], 1);
            }
        }
 
        // Check if it is valid
        if (occ.Count == 2) {
            int x = -1, y = -1;
            foreach (char item in occ.Keys) {
                if (x == -1)
                    x = occ[item];
                else
                    y = occ[item];
            }
 
            // Count of one of the chars is
            // greater than k/3
            if (x >= k / 3 && y >= k / 3) {
                Console.WriteLine("YES");
                return;
            }
        }
 
        // Sliding over the entire string
        for (int i = k; i < n; i++) {
 
            // Discarding first character of
            // previous window
            occ[S[i - k] ]= occ[S[i - k]] - 1;
 
            // Erase it from the map, if its
            // frequency becomes 0
            if (occ[S[i - k]] == 0)
                occ.Remove(S[i - k]);
 
            // Increment count of current char
            if (occ.ContainsKey(S[i])) {
                occ[S[i]] = occ[S[i]] + 1;
            } else {
                occ.Add(S[i], 1);
            }
 
            // Checking valid or not
            if (occ.Count == 2) {
                int x = -1, y = -1;
                foreach (char item in occ.Keys) {
                    if (x == -1)
                        x = occ[item];
                    else
                        y = occ[item];
                }
 
                if (x >= k / 3 && y >= k / 3) {
                    Console.WriteLine("YES");
                    return;
                }
            }
        }
 
        // No valid substring is found
        Console.WriteLine("NO");
    }
 
    // Driver Code
    public static void Main(String []args) {
        int K = 6;
        String S = "abaaaa";
        checkGoldenString(S, K);
 
        K = 4;
        S = "abbaaaa";
        checkGoldenString(S, K);
    }
}
 
// This code is contributed by shikhasingrajput


Javascript



输出
NO
YES

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