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

📅  最后修改于: 2021-10-27 09:21:50             🧑  作者: Mango

给定一个字符串S ,任务是打印给定字符串第一个和最后一个字符不同的子字符串的数量。

例子:

朴素的方法:这个想法是生成给定字符串的所有可能的子字符串,对于每个子字符串,检查第一个和最后一个字符是否不同。如果发现为真,则将计数增加 1 并检查下一个子字符串。遍历所有子串后打印计数。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to count the substrings
// having different first and last
// characters
int countSubstring(string s, int n)
{
    // Store the final count
    int ans = 0;
 
    // Loop to traverse the string
    for (int i = 0; i < n; i++) {
 
        // Counter for each iteration
        int cnt = 0;
 
        // Iterate over substrings
        for (int j = i + 1; j < n; j++) {
 
            // Compare the characters
            if (s[j] != s[i])
 
                // Increase count
                cnt++;
        }
 
        // Adding count of substrings
        // to the final count
        ans += cnt;
    }
 
    // Print the final count
    cout << ans;
}
 
// Driver Code
int main()
{
    // Given string
    string S = "abcab";
 
    // Length of the string
    int N = 5;
 
    // Function Call
    countSubstring(S, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG{
     
// Function to count the substrings
// having different first and last
// characters
static void countSubstring(String s, int n)
{
     
    // Store the final count
    int ans = 0;
 
    // Loop to traverse the string
    for(int i = 0; i < n; i++)
    {
         
        // Counter for each iteration
        int cnt = 0;
 
        // Iterate over substrings
        for(int j = i + 1; j < n; j++)
        {
             
            // Compare the characters
            if (s.charAt(j) != s.charAt(i))
 
                // Increase count
                cnt++;
        }
 
        // Adding count of substrings
        // to the final count
        ans += cnt;
    }
 
    // Print the final count
    System.out.print(ans);
}
     
// Driver Code
public static void main(String[] args)
{
     
    // Given string
    String S = "abcab";
 
    // Length of the string
    int N = 5;
 
    // Function call
    countSubstring(S, N);
}
}
 
// This code is contributed by code_hunt


Python3
# Python3 program for the above approach
 
# Function to count the substrings
# having different first and last
# characters
def countSubstring(s, n):
 
    # Store the final count
    ans = 0
 
    # Loop to traverse the string
    for i in range(n):
 
        # Counter for each iteration
        cnt = 0
 
        # Iterate over substrings
        for j in range(i + 1, n):
 
            # Compare the characters
            if (s[j] != s[i]):
 
                # Increase count
                cnt += 1
         
        # Adding count of substrings
        # to the final count
        ans += cnt
     
    # Print the final count
    print(ans)
 
# Driver Code
 
# Given string
S = "abcab"
 
# Length of the string
N = 5
 
# Function call
countSubstring(S, N)
 
# This code is contributed by code_hunt


C#
// C# program for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
 
class GFG{
     
// Function to count the substrings
// having different first and last
// characters
static void countSubstring(string s, int n)
{
     
    // Store the final count
    int ans = 0;
 
    // Loop to traverse the string
    for(int i = 0; i < n; i++)
    {
         
        // Counter for each iteration
        int cnt = 0;
 
        // Iterate over substrings
        for(int j = i + 1; j < n; j++)
        {
             
            // Compare the characters
            if (s[j] != s[i])
 
                // Increase count
                cnt++;
        }
 
        // Adding count of substrings
        // to the final count
        ans += cnt;
    }
 
    // Print the final count
    Console.Write(ans);
}
     
// Driver Code
public static void Main(string[] args)
{
     
    // Given string
    string S = "abcab";
 
    // Length of the string
    int N = 5;
 
    // Function call
    countSubstring(S, N);
}
}
 
// This code is contributed by rutvik_56


Javascript


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to count the substrings
// having different first & last character
int countSubstring(string s, int n)
{
    // Stores frequency of each char
    map m;
 
    // Loop to store frequency of
    // the characters in a Map
    for (int i = 0; i < n; i++)
        m[s[i]]++;
 
    // To store final result
    int ans = 0;
 
    // Traversal of string
    for (int i = 0; i < n; i++) {
 
        // Store answer for every
        // iteration
        int cnt = 0;
        m[s[i]]--;
 
        // Map traversal
        for (auto value : m) {
 
            // Compare current char
            if (value.first == s[i]) {
                continue;
            }
            else {
                cnt += value.second;
            }
        }
 
        ans += cnt;
    }
 
    // Print the final count
    cout << ans;
}
 
// Driver Code
int main()
{
    // Given string
    string S = "abcab";
 
    // Length of the string
    int N = 5;
 
    // Function Call
    countSubstring(S, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to count the subStrings
// having different first & last character
static void countSubString(char []s, int n)
{
     
    // Stores frequency of each char
    HashMap mp = new HashMap();
 
    // Loop to store frequency of
    // the characters in a Map
    for(int i = 0; i < n; i++)
 
        if (mp.containsKey(s[i]))
        {
            mp.put(s[i], mp.get(s[i]) + 1);
        }
        else
        {
            mp.put(s[i], 1);
        }
 
    // To store final result
    int ans = 0;
 
    // Traversal of String
    for(int i = 0; i < n; i++)
    {
         
        // Store answer for every
        // iteration
        int cnt = 0;
        if (mp.containsKey(s[i]))
        {
            mp.put(s[i], mp.get(s[i]) - 1);
 
            // Map traversal
            for(Map.Entry value : mp.entrySet())
            {
                 
                // Compare current char
                if (value.getKey() == s[i])
                {
                    continue;
                }
                else
                {
                    cnt += value.getValue();
                }
            }
            ans += cnt;
        }
    }
     
    // Print the final count
    System.out.print(ans);
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given String
    String S = "abcab";
 
    // Length of the String
    int N = 5;
 
    // Function call
    countSubString(S.toCharArray(), N);
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 program for the above approach
 
# Function to count the substrings
# having different first & last character
def countSubstring(s, n):
  
    # Stores frequency of each char
    m = {}
 
    # Loop to store frequency of
    # the characters in a Map
    for i in range(n):
        if s[i] in m:
            m[s[i]] += 1
        else:
            m[s[i]] = 1
 
    # To store final result
    ans = 0
 
    # Traversal of string
    for i in range(n):
 
        # Store answer for every
        # iteration
        cnt = 0
         
        if s[i] in m:
            m[s[i]] -= 1
        else:
            m[s[i]] = -1
 
        # Map traversal
        for value in m:
 
            # Compare current char
            if (value == s[i]):
                continue
            else:
                cnt += m[value]
 
        ans += cnt
 
    # Print the final count
    print(ans)
 
# Driver code
 
# Given string
S = "abcab"
 
# Length of the string
N = 5
 
# Function Call
countSubstring(S, N)
 
# This code is contributed by divyeshrabadiya07


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count the subStrings
// having different first & last character
static void countSubString(char []s, int n)
{
     
    // Stores frequency of each char
    Dictionary mp = new Dictionary();
 
    // Loop to store frequency of
    // the characters in a Map
    for(int i = 0; i < n; i++)
 
        if (mp.ContainsKey(s[i]))
        {
            mp[s[i]] = mp[s[i]] + 1;
        }
        else
        {
            mp.Add(s[i], 1);
        }
 
    // To store readonly result
    int ans = 0;
 
    // Traversal of String
    for(int i = 0; i < n; i++)
    {
         
        // Store answer for every
        // iteration
        int cnt = 0;
        if (mp.ContainsKey(s[i]))
        {
            mp[s[i]] = mp[s[i]] - 1;
 
            // Map traversal
            foreach(KeyValuePair value in mp)
            {
                 
                // Compare current char
                if (value.Key == s[i])
                {
                    continue;
                }
                else
                {
                    cnt += value.Value;
                }
            }
            ans += cnt;
        }
    }
     
    // Print the readonly count
    Console.Write(ans);
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given String
    String S = "abcab";
 
    // Length of the String
    int N = 5;
 
    // Function call
    countSubString(S.ToCharArray(), N);
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
8

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

高效的方法:可以使用 Map by 来优化上述方法来存储字符串的字符的频率。请按照以下步骤解决问题:

  1. 初始化两个变量,一个用于为每次迭代计算不同的字符(例如cur ),另一个用于存储子字符串的最终计数(例如ans )。
  2. 初始化一个映射M来存储其中所有字符的频率。
  3. 遍历给定的字符串和每个字符,按照以下步骤操作:
    • 迭代映射M
    • 如果第一个元素即地图的与当前字符,则继续。
    • 否则,添加当前字符对应的值。
  4. 在遍历Map 之后,将cur添加到最终结果中,即ans += cur

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to count the substrings
// having different first & last character
int countSubstring(string s, int n)
{
    // Stores frequency of each char
    map m;
 
    // Loop to store frequency of
    // the characters in a Map
    for (int i = 0; i < n; i++)
        m[s[i]]++;
 
    // To store final result
    int ans = 0;
 
    // Traversal of string
    for (int i = 0; i < n; i++) {
 
        // Store answer for every
        // iteration
        int cnt = 0;
        m[s[i]]--;
 
        // Map traversal
        for (auto value : m) {
 
            // Compare current char
            if (value.first == s[i]) {
                continue;
            }
            else {
                cnt += value.second;
            }
        }
 
        ans += cnt;
    }
 
    // Print the final count
    cout << ans;
}
 
// Driver Code
int main()
{
    // Given string
    string S = "abcab";
 
    // Length of the string
    int N = 5;
 
    // Function Call
    countSubstring(S, N);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to count the subStrings
// having different first & last character
static void countSubString(char []s, int n)
{
     
    // Stores frequency of each char
    HashMap mp = new HashMap();
 
    // Loop to store frequency of
    // the characters in a Map
    for(int i = 0; i < n; i++)
 
        if (mp.containsKey(s[i]))
        {
            mp.put(s[i], mp.get(s[i]) + 1);
        }
        else
        {
            mp.put(s[i], 1);
        }
 
    // To store final result
    int ans = 0;
 
    // Traversal of String
    for(int i = 0; i < n; i++)
    {
         
        // Store answer for every
        // iteration
        int cnt = 0;
        if (mp.containsKey(s[i]))
        {
            mp.put(s[i], mp.get(s[i]) - 1);
 
            // Map traversal
            for(Map.Entry value : mp.entrySet())
            {
                 
                // Compare current char
                if (value.getKey() == s[i])
                {
                    continue;
                }
                else
                {
                    cnt += value.getValue();
                }
            }
            ans += cnt;
        }
    }
     
    // Print the final count
    System.out.print(ans);
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Given String
    String S = "abcab";
 
    // Length of the String
    int N = 5;
 
    // Function call
    countSubString(S.toCharArray(), N);
}
}
 
// This code is contributed by Amit Katiyar

蟒蛇3

# Python3 program for the above approach
 
# Function to count the substrings
# having different first & last character
def countSubstring(s, n):
  
    # Stores frequency of each char
    m = {}
 
    # Loop to store frequency of
    # the characters in a Map
    for i in range(n):
        if s[i] in m:
            m[s[i]] += 1
        else:
            m[s[i]] = 1
 
    # To store final result
    ans = 0
 
    # Traversal of string
    for i in range(n):
 
        # Store answer for every
        # iteration
        cnt = 0
         
        if s[i] in m:
            m[s[i]] -= 1
        else:
            m[s[i]] = -1
 
        # Map traversal
        for value in m:
 
            # Compare current char
            if (value == s[i]):
                continue
            else:
                cnt += m[value]
 
        ans += cnt
 
    # Print the final count
    print(ans)
 
# Driver code
 
# Given string
S = "abcab"
 
# Length of the string
N = 5
 
# Function Call
countSubstring(S, N)
 
# This code is contributed by divyeshrabadiya07

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count the subStrings
// having different first & last character
static void countSubString(char []s, int n)
{
     
    // Stores frequency of each char
    Dictionary mp = new Dictionary();
 
    // Loop to store frequency of
    // the characters in a Map
    for(int i = 0; i < n; i++)
 
        if (mp.ContainsKey(s[i]))
        {
            mp[s[i]] = mp[s[i]] + 1;
        }
        else
        {
            mp.Add(s[i], 1);
        }
 
    // To store readonly result
    int ans = 0;
 
    // Traversal of String
    for(int i = 0; i < n; i++)
    {
         
        // Store answer for every
        // iteration
        int cnt = 0;
        if (mp.ContainsKey(s[i]))
        {
            mp[s[i]] = mp[s[i]] - 1;
 
            // Map traversal
            foreach(KeyValuePair value in mp)
            {
                 
                // Compare current char
                if (value.Key == s[i])
                {
                    continue;
                }
                else
                {
                    cnt += value.Value;
                }
            }
            ans += cnt;
        }
    }
     
    // Print the readonly count
    Console.Write(ans);
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given String
    String S = "abcab";
 
    // Length of the String
    int N = 5;
 
    // Function call
    countSubString(S.ToCharArray(), N);
}
}
 
// This code is contributed by Amit Katiyar

Javascript


输出:
8

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程