给定一个字符串S,我们需要找到所有以相同字符开始和结束的连续子字符串的计数。
例子 :
Input : S = "abcab"
Output : 7
There are 15 substrings of "abcab"
a, ab, abc, abca, abcab, b, bc, bca
bcab, c, ca, cab, a, ab, b
Out of the above substrings, there
are 7 substrings : a, abca, b, bcab,
c, a and b.
Input : S = "aba"
Output : 4
The substrings are a, b, a and aba
我们在下面的文章中讨论了不同的解决方案。
计算具有相同首尾字符的子字符串
在本文中,讨论了一个简单的递归解决方案。
C++
// c++ program to count substrings with same
// first and last characters
#include
#include
using namespace std;
/* Function to count subtrings with same first and
last characters*/
int countSubstrs(string str, int i, int j, int n)
{
// base cases
if (n == 1)
return 1;
if (n <= 0)
return 0;
int res = countSubstrs(str, i + 1, j, n - 1) +
countSubstrs(str, i, j - 1, n - 1) -
countSubstrs(str, i + 1, j - 1, n - 2);
if (str[i] == str[j])
res++;
return res;
}
// driver code
int main()
{
string str = "abcab";
int n = str.length();
cout << countSubstrs(str, 0, n - 1, n);
}
Java
// Java program to count substrings
// with same first and last characters
class GFG
{
// Function to count subtrings
// with same first and
// last characters
static int countSubstrs(String str, int i,
int j, int n)
{
// base cases
if (n == 1)
return 1;
if (n <= 0)
return 0;
int res = countSubstrs(str, i + 1, j, n - 1) +
countSubstrs(str, i, j - 1, n - 1) -
countSubstrs(str, i + 1, j - 1, n - 2);
if (str.charAt(i) == str.charAt(j))
res++;
return res;
}
// Driver code
public static void main (String[] args)
{
String str = "abcab";
int n = str.length();
System.out.print(countSubstrs(str, 0, n - 1, n));
}
}
// This code is contributed by Anant Agarwal.
Python 3
# Python 3 program to count substrings with same
# first and last characters
# Function to count subtrings with same first and
# last characters
def countSubstrs(str, i, j, n):
# base cases
if (n == 1):
return 1
if (n <= 0):
return 0
res = (countSubstrs(str, i + 1, j, n - 1)
+ countSubstrs(str, i, j - 1, n - 1)
- countSubstrs(str, i + 1, j - 1, n - 2))
if (str[i] == str[j]):
res += 1
return res
# driver code
str = "abcab"
n = len(str)
print(countSubstrs(str, 0, n - 1, n))
# This code is contributed by Smitha
C#
// C# program to count substrings
// with same first and last characters
using System;
class GFG {
// Function to count subtrings
// with same first and
// last characters
static int countSubstrs(string str, int i,
int j, int n)
{
// base cases
if (n == 1)
return 1;
if (n <= 0)
return 0;
int res = countSubstrs(str, i + 1, j, n - 1)
+ countSubstrs(str, i, j - 1, n - 1)
- countSubstrs(str, i + 1, j - 1, n - 2);
if (str[i] == str[j])
res++;
return res;
}
// Driver code
public static void Main ()
{
string str = "abcab";
int n = str.Length;
Console.WriteLine(
countSubstrs(str, 0, n - 1, n));
}
}
// This code is contributed by vt_m.
PHP
输出:
7
上述解决方案的时间复杂度是指数的。在最坏的情况下,我们可能最终会执行O(3 n )运算。