查找具有N个字符的字符串的非空子字符串的总数。在这里,我们使用“适当”一词,因为我们不将字符串本身视为输出的一部分。
Input : str = “abc”
Output : 6
Proper substrings are “a”, “b”, “c”, “ab”, “bc”, “abc”
Input : str = “abcd”
Output : 10
Proper substrings are “a”, “b”, “c”, “d”, “ab”, “bc”, “cd”, “abc”, “bcd” and “abcd”
非空子字符串的计数为n *(n + 1)/ 2
如果我们也将空字符串作为子字符串包括在内,则计数变为n *(n + 1)/ 2 + 1
以上公式如何运作?
- 长度为1的子字符串数为n (我们可以选择n个字符的任何一个)
- 长度为2的子串的数量为n-1 (我们可以选择相邻的n-1个对中的任何一个)
- 长度为三的子串的数量为n-2
(我们可以选择相邻的n-2个三元组中的任何一个) - 通常,长度为k的子串的成员为n-k + 1 ,其中1 <= k <= n
从1到n的所有长度的子字符串的总数=
n +(n-1)+(n-2)+(n-3)+…2 + 1
= n *(n + 1)/ 2
C++
// CPP program to count number of substrings
// of a string
#include
using namespace std;
int countNonEmptySubstr(string str)
{
int n = str.length();
return n*(n+1)/2;
}
// driver code
int main()
{
string s = "abcde";
cout << countNonEmptySubstr(s);
return 0;
}
Java
// Java program to count number of substrings
// of a string
import java.io.*;
public class GFG {
static int countNonEmptySubstr(String str)
{
int n = str.length();
return n * (n + 1) / 2;
}
// Driver code
public static void main(String args[])
{
String s = "abcde";
System.out.println(
countNonEmptySubstr(s));
}
}
// This code is contributed
// by Manish Shaw (manishshaw1)
Python3
# Python3 program to count number
# of substrings of a string
def countNonEmptySubstr(str):
n = len(str);
return int(n * (n + 1) / 2);
# driver code
s = "abcde";
print (countNonEmptySubstr(s));
# This code is contributed by
# Manish Shaw (manishshaw1)
C#
// C# program to count number
// of substrings of a string
using System;
class GFG {
static int countNonEmptySubstr(string str)
{
int n = str.Length;
return n * (n + 1) / 2;
}
// Driver Code
public static void Main()
{
string s = "abcde";
Console.Write(countNonEmptySubstr(s));
}
}
// This code is contributed
// by Manish Shaw (manishshaw1)
PHP
输出:
15