📌  相关文章
📜  计算具有相同首尾字符的子字符串

📅  最后修改于: 2021-05-04 13:15:26             🧑  作者: Mango

给定一个字符串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

方法1(简单):在这种方法中,我们使用蛮力查找所有子字符串,并将它们通过我们的函数checkEquality传递,以查看起始字符和结束字符是否相同。

C++
// C++ program to count all substrings with same
// first and last characters.
#include 
using namespace std;
  
// Returns true if first and last characters
// of s are same.
int checkEquality(string s)
{
    return (s[0] == s[s.size() - 1]);
}
  
int countSubstringWithEqualEnds(string s)
{
    int result = 0;
    int n = s.length();
  
    // Starting point of substring
    for (int i = 0; i < n; i++)
  
       // Length of substring
       for (int len = 1; len <= n-i; len++)
  
          // Check if current substring has same
          // starting and ending characters.
          if (checkEquality(s.substr(i, len)))
            result++;
  
    return result;
}
  
// Driver function
int main()
{
    string s("abcab");
    cout << countSubstringWithEqualEnds(s);
    return 0;
}


Java
// Java program to count all substrings with same
// first and last characters.
public class GFG {
   
    // Returns true if first and last characters
    // of s are same.
    static boolean checkEquality(String s)
    {
        return (s.charAt(0) == s.charAt(s.length() - 1));
    }
       
    static int countSubstringWithEqualEnds(String s)
    {
        int result = 0;
        int n = s.length();
       
        // Starting point of substring
        for (int i = 0; i < n; i++)
       
           // Length of substring
           for (int len = 1; len <= n-i; len++)
       
              // Check if current substring has same
              // starting and ending characters.
              if (checkEquality(s.substring(i, i + len)))
                result++;
       
        return result;
    }
       
    // Driver function
    public static void main(String args[])
    {
        String s = "abcab";
        System.out.println(countSubstringWithEqualEnds(s));
    }
}
// This code is contributed by Sumit Ghosh


Python3
# Python program to count all substrings with same
# first and last characters.
  
# Returns true if first and last characters
# of s are same.
def checkEquality(s):
    return (ord(s[0]) == ord(s[len(s) - 1]));
  
def countSubstringWithEqualEnds(s):
    result = 0;
    n = len(s);
  
    # Starting poof substring
    for i in range(n):
  
    # Length of substring
        for j in range(1,n-i+1):
  
        # Check if current substring has same
        # starting and ending characters.
            if (checkEquality(s[i:i+j])):
                result+=1;
  
    return result;
  
# Driver code
s = "abcab";
print(countSubstringWithEqualEnds(s));
  
# This code contributed by PrinciRaj1992


C#
// C# program to count all
// substrings with same
// first and last characters.
using System;
  
class GFG 
{
  
    // Returns true if first and
    //  last characters of s are same.
    static bool checkEquality(string s)
    {
        return (s[0] == s[s.Length - 1]);
    }
      
    static int countSubstringWithEqualEnds(string s)
    {
        int result = 0;
        int n = s.Length;
      
        // Starting point of substring
        for (int i = 0; i < n; i++)
      
        // Length of substring
        for (int len = 1; len <= n-i; len++)
      
            // Check if current substring has same
            // starting and ending characters.
            if (checkEquality(s.Substring(i, len)))
                result++;
      
        return result;
    }
      
    // Driver code
    public static void Main()
    {
        string s = "abcab";
        Console.WriteLine(countSubstringWithEqualEnds(s));
    }
}
  
// This code is contributed by Code_Mech


PHP


C++
// Space efficient C++ program to count all
// substrings with same first and last characters.
#include 
using namespace std;
  
int countSubstringWithEqualEnds(string s)
{
    int result = 0;
    int n = s.length();
  
    // Iterating through all substrings in
    // way so that we can find first and last
    // character easily
    for (int i=0; i


Java
// Space efficient Java program to count all
// substrings with same first and last characters.
public class GFG {
    
    static int countSubstringWithEqualEnds(String s)
    {
        int result = 0;
        int n = s.length();
       
        // Iterating through all substrings in
        // way so that we can find first and last
        // character easily
        for (int i = 0; i < n; i++)
            for (int j = i; j < n; j++)
                if (s.charAt(i) == s.charAt(j))
                    result++;
       
        return result;
    }
       
    // Driver function
    public static void main(String args[])
    {
        String s = "abcab";
        System.out.println(countSubstringWithEqualEnds(s));
    }
}
// This code is contributed by Sumit Ghosh


Python3
# Space efficient Python3 program to count all
# substrings with same first and last characters.
def countSubstringWithEqualEnds(s):
  
    result = 0;
    n = len(s);
  
    # Iterating through all substrings in
    # way so that we can find first and 
    # last character easily
    for i in range(n):
        for j in range(i, n):
            if (s[i] == s[j]):
                result = result + 1
  
    return result
  
# Driver Code
s = "abcab";
print(countSubstringWithEqualEnds(s))
  
# This code is contributed 
# by Akanksha Rai


C#
// Space efficient C# program to count all
// substrings with same first and last characters.
using System;
  
public class GFG {
     
    static int countSubstringWithEqualEnds(string s)
    {
        int result = 0;
        int n = s.Length;
        
        // Iterating through all substrings in
        // way so that we can find first and last
        // character easily
        for (int i = 0; i < n; i++)
            for (int j = i; j < n; j++)
                if (s[i] == s[j])
                    result++;
        
        return result;
    }
        
    // Driver function
    public static void Main()
    {
        string s = "abcab";
        Console.Write(countSubstringWithEqualEnds(s));
    }
}
  
// This code is contributed by nitin mittal


PHP


C++
// Most efficient C++ program to count all  
// substrings with same first and last characters.
#include 
using namespace std;
const int MAX_CHAR = 26;  // assuming lower case only
  
int countSubstringWithEqualEnds(string s)
{
    int result = 0;
    int n = s.length();
  
    // Calculating frequency of each character
    // in the string.
    int count[MAX_CHAR] = {0};
    for (int i=0; i


Java
// Most efficient Java program to count all  
// substrings with same first and last characters.
public class GFG {
          
      // assuming lower case only
    static final int MAX_CHAR = 26;  
       
    static int countSubstringWithEqualEnds(String s)
    {
        int result = 0;
        int n = s.length();
       
        // Calculating frequency of each character
        // in the string.
        int[] count =  new int[MAX_CHAR];
        for (int i = 0; i < n; i++)
            count[s.charAt(i)-'a']++;
       
        // Computing result using counts
        for (int i = 0; i < MAX_CHAR; i++)
            result += (count[i] * (count[i] + 1) / 2);
       
        return result;
    }
       
    // Driver function
    public static void main(String args[])
    {
        String s = "abcab";
        System.out.println(countSubstringWithEqualEnds(s));
    }
}
// This code is contributed by Sumit Ghosh


Python3
# Most efficient Python program to count all 
# substrings with same first and last characters.
  
MAX_CHAR = 26; # assuming lower case only
  
def countSubstringWithEqualEnds(s):
    result = 0;
    n = len(s);
  
    # Calculating frequency of each character
    # in the string.
    count = [0]*MAX_CHAR;
    for i in range(n):
        count[ord(s[i])-ord('a')]+=1;
  
    # Computing result using counts
    for i in range(MAX_CHAR):
        result += (count[i]*(count[i]+1)/2);
  
    return result;
  
# Driver code
s = "abcab";
print(countSubstringWithEqualEnds(s));
  
  
# This code is contributed by 29AjayKumar


C#
// Most efficient C# program to count all 
// substrings with same first and last characters.
using System;
      
class GFG {
          
    // assuming lower case only
    static readonly int MAX_CHAR = 26; 
      
    static int countSubstringWithEqualEnds(String s)
    {
        int result = 0;
        int n = s.Length;
      
        // Calculating frequency of each character
        // in the string.
        int[] count = new int[MAX_CHAR];
        for (int i = 0; i < n; i++)
            count[s[i] - 'a']++;
      
        // Computing result using counts
        for (int i = 0; i < MAX_CHAR; i++)
            result += (count[i] * (count[i] + 1) / 2);
      
        return result;
    }
      
    // Driver code
    public static void Main()
    {
        String s = "abcab";
        Console.Write(countSubstringWithEqualEnds(s));
    }
}
  
// This code is contributed by 29AjayKumar


PHP


输出:

7

尽管上面的代码可以正常工作,但是效率不高,因为它的时间复杂度是O(n 2 )。请注意,存在长度为n的字符串的n *(n + 1)/ 2个子字符串。此解决方案还需要O(n)额外的空间,因为我们一个一个地创建了所有子字符串。

方法2(高效空间):在这种方法中,我们实际上并不生成子字符串,而是以这种方式遍历字符串,以便我们可以轻松地比较第一个和最后一个字符。

C++

// Space efficient C++ program to count all
// substrings with same first and last characters.
#include 
using namespace std;
  
int countSubstringWithEqualEnds(string s)
{
    int result = 0;
    int n = s.length();
  
    // Iterating through all substrings in
    // way so that we can find first and last
    // character easily
    for (int i=0; i

Java

// Space efficient Java program to count all
// substrings with same first and last characters.
public class GFG {
    
    static int countSubstringWithEqualEnds(String s)
    {
        int result = 0;
        int n = s.length();
       
        // Iterating through all substrings in
        // way so that we can find first and last
        // character easily
        for (int i = 0; i < n; i++)
            for (int j = i; j < n; j++)
                if (s.charAt(i) == s.charAt(j))
                    result++;
       
        return result;
    }
       
    // Driver function
    public static void main(String args[])
    {
        String s = "abcab";
        System.out.println(countSubstringWithEqualEnds(s));
    }
}
// This code is contributed by Sumit Ghosh

Python3

# Space efficient Python3 program to count all
# substrings with same first and last characters.
def countSubstringWithEqualEnds(s):
  
    result = 0;
    n = len(s);
  
    # Iterating through all substrings in
    # way so that we can find first and 
    # last character easily
    for i in range(n):
        for j in range(i, n):
            if (s[i] == s[j]):
                result = result + 1
  
    return result
  
# Driver Code
s = "abcab";
print(countSubstringWithEqualEnds(s))
  
# This code is contributed 
# by Akanksha Rai

C#

// Space efficient C# program to count all
// substrings with same first and last characters.
using System;
  
public class GFG {
     
    static int countSubstringWithEqualEnds(string s)
    {
        int result = 0;
        int n = s.Length;
        
        // Iterating through all substrings in
        // way so that we can find first and last
        // character easily
        for (int i = 0; i < n; i++)
            for (int j = i; j < n; j++)
                if (s[i] == s[j])
                    result++;
        
        return result;
    }
        
    // Driver function
    public static void Main()
    {
        string s = "abcab";
        Console.Write(countSubstringWithEqualEnds(s));
    }
}
  
// This code is contributed by nitin mittal

的PHP

输出:

7

在上面的代码中,尽管我们将多余的空间减少到O(1),但是时间复杂度仍然是O(n ^ 2)。

方法3(最佳方法):现在,如果我们仔细观察,就会发现答案仅取决于原始字符串中字符的频率。例如,在字符串abcab中,频率“ a”为2,而有助于回答的子字符串分别为a,abca和a,总计为3,这由(频率“ a” +1) C 2计算得出。

C++

// Most efficient C++ program to count all  
// substrings with same first and last characters.
#include 
using namespace std;
const int MAX_CHAR = 26;  // assuming lower case only
  
int countSubstringWithEqualEnds(string s)
{
    int result = 0;
    int n = s.length();
  
    // Calculating frequency of each character
    // in the string.
    int count[MAX_CHAR] = {0};
    for (int i=0; i

Java

// Most efficient Java program to count all  
// substrings with same first and last characters.
public class GFG {
          
      // assuming lower case only
    static final int MAX_CHAR = 26;  
       
    static int countSubstringWithEqualEnds(String s)
    {
        int result = 0;
        int n = s.length();
       
        // Calculating frequency of each character
        // in the string.
        int[] count =  new int[MAX_CHAR];
        for (int i = 0; i < n; i++)
            count[s.charAt(i)-'a']++;
       
        // Computing result using counts
        for (int i = 0; i < MAX_CHAR; i++)
            result += (count[i] * (count[i] + 1) / 2);
       
        return result;
    }
       
    // Driver function
    public static void main(String args[])
    {
        String s = "abcab";
        System.out.println(countSubstringWithEqualEnds(s));
    }
}
// This code is contributed by Sumit Ghosh

Python3

# Most efficient Python program to count all 
# substrings with same first and last characters.
  
MAX_CHAR = 26; # assuming lower case only
  
def countSubstringWithEqualEnds(s):
    result = 0;
    n = len(s);
  
    # Calculating frequency of each character
    # in the string.
    count = [0]*MAX_CHAR;
    for i in range(n):
        count[ord(s[i])-ord('a')]+=1;
  
    # Computing result using counts
    for i in range(MAX_CHAR):
        result += (count[i]*(count[i]+1)/2);
  
    return result;
  
# Driver code
s = "abcab";
print(countSubstringWithEqualEnds(s));
  
  
# This code is contributed by 29AjayKumar

C#

// Most efficient C# program to count all 
// substrings with same first and last characters.
using System;
      
class GFG {
          
    // assuming lower case only
    static readonly int MAX_CHAR = 26; 
      
    static int countSubstringWithEqualEnds(String s)
    {
        int result = 0;
        int n = s.Length;
      
        // Calculating frequency of each character
        // in the string.
        int[] count = new int[MAX_CHAR];
        for (int i = 0; i < n; i++)
            count[s[i] - 'a']++;
      
        // Computing result using counts
        for (int i = 0; i < MAX_CHAR; i++)
            result += (count[i] * (count[i] + 1) / 2);
      
        return result;
    }
      
    // Driver code
    public static void Main()
    {
        String s = "abcab";
        Console.Write(countSubstringWithEqualEnds(s));
    }
}
  
// This code is contributed by 29AjayKumar

的PHP


输出:

7

上面的代码具有O(n)的时间复杂度,并且需要O(1)额外的空间。

递归解决方案,以计数具有相同的首尾字符的子字符串