📌  相关文章
📜  可被K整除的子字符串的计数

📅  最后修改于: 2021-05-31 19:30:02             🧑  作者: Mango

给定一个整数K和一个数字字符串str (所有字符都在[‘0’,’9’]范围内)。任务是计算可被K整除的str子字符串的数量。
例子:

方法:初始化count = 0 。取所有str的子字符串,并检查它们是否可被K整除。如果是,则更新count = count +1 。最后打印计数
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the count of sub-strings
// of str that are divisible by k
int countSubStr(string str, int len, int k)
{
    int count = 0;
  
    for (int i = 0; i < len; i++) 
    {
        int n = 0;
  
        // Take all sub-strings starting from i
        for (int j = i; j < len; j++) 
        {
            n = n * 10 + (str[j] - '0');
  
            // If current sub-string is divisible by k
            if (n % k == 0)
                count++;
        }
    }
  
    // Return the required count
    return count;
}
  
// Driver code
int main()
{
    string str = "33445";
    int len = str.length();
    int k = 11;
    cout << countSubStr(str, len, k);
  
    return 0;
}


Java
// Java implementation of above approach 
class GFG
{
  
    // Function to return the count of sub-strings 
    // of str that are divisible by k 
    static int countSubStr(String str, int len, int k) 
    { 
        int count = 0; 
      
        for (int i = 0; i < len; i++) 
        { 
            int n = 0; 
      
            // Take all sub-strings starting from i 
            for (int j = i; j < len; j++)
            { 
                n = n * 10 + (str.charAt(j) - '0'); 
      
                // If current sub-string is divisible by k 
                if (n % k == 0) 
                    count++; 
            } 
        } 
      
        // Return the required count 
        return count; 
    } 
  
    // Driver code 
    public static void main(String []args)
    { 
        String str = "33445"; 
        int len = str.length(); 
        int k = 11; 
        System.out.println(countSubStr(str, len, k)); 
    } 
}
  
// This code is contributed by Ryuga


Python3
# Python 3 implementation of the approach
  
# Function to return the count of sub-strings
# of str that are divisible by k
def countSubStr(str, l, k):
    count = 0
  
    for i in range(l):
        n = 0
  
        # Take all sub-strings starting from i
        for j in range(i, l, 1):
            n = n * 10 + (ord(str[j]) - ord('0'))
  
            # If current sub-string is divisible by k
            if (n % k == 0):
                count += 1
      
    # Return the required count
    return count
  
# Driver code
if __name__ == '__main__':
    str = "33445"
    l = len(str)
    k = 11
    print(countSubStr(str, l, k))
  
# This code is contributed by
# Sanjit_Prasad


C#
// C# implementation of above approach 
using System;
  
class GFG
{
  
    // Function to return the count of sub-strings 
    // of str that are divisible by k 
    static int countSubStr(String str, int len, int k) 
    { 
        int count = 0; 
      
        for (int i = 0; i < len; i++) 
        { 
            int n = 0; 
      
            // Take all sub-strings starting from i 
            for (int j = i; j < len; j++)
            { 
                n = n * 10 + (str[j] - '0'); 
      
                // If current sub-string is divisible by k 
                if (n % k == 0) 
                    count++; 
            } 
        } 
      
        // Return the required count 
        return count; 
    } 
  
    // Driver code 
    public static void Main()
    { 
        String str = "33445"; 
        int len = str.Length; 
        int k = 11; 
        Console.WriteLine(countSubStr(str, len, k)); 
    } 
}
  
// This code is contributed by Code_Mech


PHP


Java
// Java Program for above approach
import java.util.*;
public class Main 
{
    
  // Program to count number of subtrings
  public static int Divisible(String s, 
                                    int k)
  {
  
    // To count substrings
    int num_of_substrings = 0;
      
    // To store the remainders
    int rem[] = new int[k];
      
    rem[0] = 1;
    StringBuffer curr = new StringBuffer();
      
    // Iterate from s.length() - 1 to 0
    for (int i = s.length() - 1; i >= 0; i--) 
    {
        
      // to Calculate suffix string
      curr.insert(0, s.charAt(i));
        
      // cnvert to number
      long num = Long.parseLong(curr.
                                toString());
      num_of_substrings += rem[(int)num % k];
        
      // Keep track of visited remainders
      rem[(int)num % k]++;
    }
      
    // Return number of subtrings
    return num_of_substrings;
  }
  
  // Driver Code
  public static void main(String args[])
  {
    String s = "111111";
    int k = 11;
      
    // Function Call
    System.out.println("Number of sub strings : "
                       + Divisible(s, k));
  }
}


输出
3

高效的方法:

这个想法是使用hashMap存储字符串的每个后缀的余数,以便任何后缀(如果已经存在于hashmap中)则它们之间的子字符串可被k整除。

下面是上述方法的实现。

Java

// Java Program for above approach
import java.util.*;
public class Main 
{
    
  // Program to count number of subtrings
  public static int Divisible(String s, 
                                    int k)
  {
  
    // To count substrings
    int num_of_substrings = 0;
      
    // To store the remainders
    int rem[] = new int[k];
      
    rem[0] = 1;
    StringBuffer curr = new StringBuffer();
      
    // Iterate from s.length() - 1 to 0
    for (int i = s.length() - 1; i >= 0; i--) 
    {
        
      // to Calculate suffix string
      curr.insert(0, s.charAt(i));
        
      // cnvert to number
      long num = Long.parseLong(curr.
                                toString());
      num_of_substrings += rem[(int)num % k];
        
      // Keep track of visited remainders
      rem[(int)num % k]++;
    }
      
    // Return number of subtrings
    return num_of_substrings;
  }
  
  // Driver Code
  public static void main(String args[])
  {
    String s = "111111";
    int k = 11;
      
    // Function Call
    System.out.println("Number of sub strings : "
                       + Divisible(s, k));
  }
}
输出
Number of sub strings : 9
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”