Count substrings with different first and last characters
Last Updated :
21 May, 2021
Given a string S, the task is to print the count of substrings from a given string whose first and last characters are different.
Examples:
Input: S = “abcab”
Output: 8
Explanation:
There are 8 substrings having first and last characters different {ab, abc, abcab, bc, bca, ca, cab, ab}.
Input: S = “aba”
Output: 2
Explanation:
There are 2 substrings having first and last characters different {ab, ba}.
Naive Approach: The idea is to generate all possible substrings of a given string and for each substring, check if the first and the last characters are different or not. If found to be true, then increment the count by 1 and check for the next substring. Print the count after traversal of all the substring.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSubstring(string s, int n)
{
int ans = 0;
for ( int i = 0; i < n; i++) {
int cnt = 0;
for ( int j = i + 1; j < n; j++) {
if (s[j] != s[i])
cnt++;
}
ans += cnt;
}
cout << ans;
}
int main()
{
string S = "abcab" ;
int N = 5;
countSubstring(S, N);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG{
static void countSubstring(String s, int n)
{
int ans = 0 ;
for ( int i = 0 ; i < n; i++)
{
int cnt = 0 ;
for ( int j = i + 1 ; j < n; j++)
{
if (s.charAt(j) != s.charAt(i))
cnt++;
}
ans += cnt;
}
System.out.print(ans);
}
public static void main(String[] args)
{
String S = "abcab" ;
int N = 5 ;
countSubstring(S, N);
}
}
|
Python3
def countSubstring(s, n):
ans = 0
for i in range (n):
cnt = 0
for j in range (i + 1 , n):
if (s[j] ! = s[i]):
cnt + = 1
ans + = cnt
print (ans)
S = "abcab"
N = 5
countSubstring(S, N)
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
class GFG{
static void countSubstring( string s, int n)
{
int ans = 0;
for ( int i = 0; i < n; i++)
{
int cnt = 0;
for ( int j = i + 1; j < n; j++)
{
if (s[j] != s[i])
cnt++;
}
ans += cnt;
}
Console.Write(ans);
}
public static void Main( string [] args)
{
string S = "abcab" ;
int N = 5;
countSubstring(S, N);
}
}
|
Javascript
<script>
function countSubstring(s, n)
{
let ans = 0;
for (let i = 0; i < n; i++)
{
let cnt = 0;
for (let j = i + 1; j < n; j++)
{
if (s[j] != s[i])
cnt++;
}
ans += cnt;
}
document.write(ans);
}
let S = "abcab" ;
let N = 5;
countSubstring(S, N);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized using Map by to store the frequency of the characters of the string. Follow the steps below to solve the problem:
- Initialize two variables, one for counting different characters for every iteration (say cur) and one to store the final count of substrings (say ans).
- Initialize a map M to store the frequency of all characters in it.
- Traverse the given string and for each character, follow the steps below:
- Iterate the map M.
- If the first element i.e., the key of the map is not the same as the current character, then proceed.
- Otherwise, add the value corresponding to the current character.
- After traversal of the Map, add cur to the final result i.e., ans += cur.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSubstring(string s, int n)
{
map< char , int > m;
for ( int i = 0; i < n; i++)
m[s[i]]++;
int ans = 0;
for ( int i = 0; i < n; i++) {
int cnt = 0;
m[s[i]]--;
for ( auto value : m) {
if (value.first == s[i]) {
continue ;
}
else {
cnt += value.second;
}
}
ans += cnt;
}
cout << ans;
}
int main()
{
string S = "abcab" ;
int N = 5;
countSubstring(S, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void countSubString( char []s, int n)
{
HashMap<Character,
Integer> mp = new HashMap<Character,
Integer>();
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 );
}
int ans = 0 ;
for ( int i = 0 ; i < n; i++)
{
int cnt = 0 ;
if (mp.containsKey(s[i]))
{
mp.put(s[i], mp.get(s[i]) - 1 );
for (Map.Entry<Character,
Integer> value : mp.entrySet())
{
if (value.getKey() == s[i])
{
continue ;
}
else
{
cnt += value.getValue();
}
}
ans += cnt;
}
}
System.out.print(ans);
}
public static void main(String[] args)
{
String S = "abcab" ;
int N = 5 ;
countSubString(S.toCharArray(), N);
}
}
|
Python3
def countSubstring(s, n):
m = {}
for i in range (n):
if s[i] in m:
m[s[i]] + = 1
else :
m[s[i]] = 1
ans = 0
for i in range (n):
cnt = 0
if s[i] in m:
m[s[i]] - = 1
else :
m[s[i]] = - 1
for value in m:
if (value = = s[i]):
continue
else :
cnt + = m[value]
ans + = cnt
print (ans)
S = "abcab"
N = 5
countSubstring(S, N)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void countSubString( char []s, int n)
{
Dictionary< char ,
int > mp = new Dictionary< char ,
int >();
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);
}
int ans = 0;
for ( int i = 0; i < n; i++)
{
int cnt = 0;
if (mp.ContainsKey(s[i]))
{
mp[s[i]] = mp[s[i]] - 1;
foreach (KeyValuePair< char ,
int > value in mp)
{
if (value.Key == s[i])
{
continue ;
}
else
{
cnt += value.Value;
}
}
ans += cnt;
}
}
Console.Write(ans);
}
public static void Main(String[] args)
{
String S = "abcab" ;
int N = 5;
countSubString(S.ToCharArray(), N);
}
}
|
Javascript
<script>
function countSubstring(s, n)
{
var m = new Map();
for ( var i = 0; i < n; i++)
{
if (m.has(s[i]))
m.set(s[i], m.get(s[i])+1)
else
m.set(s[i], 1)
}
var ans = 0;
for ( var i = 0; i < n; i++) {
var cnt = 0;
if (m.has(s[i]))
m.set(s[i], m.get(s[i])-1)
m.forEach((value, key) => {
if (key != s[i]) {
cnt += value;
}
});
ans += cnt;
}
document.write( ans);
}
var S = "abcab" ;
var N = 5;
countSubstring(S, N);
</script>
|
Time Complexity: O(N*26)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...