Distinct state codes that appear in a string as contiguous sub-strings
Last Updated :
27 Jan, 2023
Every state is represented by string of length 2. For example DL is used for Delhi, HP for Himachal Pradesh, UP for Uttar Pradesh, PB for Punjab etc.
Given a string str consisting of uppercase English alphabets only, the task is to find the number of distinct state codes that appear in the string as contiguous sub-strings.
Examples:
Input: str = “UPBRC”
Output: 4
UP, PB, BR and RC are 4 different state codes that appear in string as contiguous sub-strings.
Input: str = “UPUP”
Output: 2
UP and PU are the only state codes that appear in the given string.
Approach: Store every sub-string of length 2 in a set and finally return the size of the set which is the required number of distinct state codes appearing in the given string as sub-strings.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countDistinctCode(string str)
{
set<string> codes;
for ( int i = 0; i < str.length() - 1; i++)
codes.insert(str.substr(i, 2));
return codes.size();
}
int main()
{
string str = "UPUP" ;
cout << countDistinctCode(str);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int countDistinctCode(String str)
{
Set<String> codes = new HashSet<>();
for ( int i = 0 ; i < str.length() - 1 ; i++)
codes.add(str.substring(i, i + 2 ));
return codes.size();
}
public static void main(String[] args)
{
String str = "UPUP" ;
System.out.println(countDistinctCode(str));
}
}
|
Python3
def countDistinctCode(string):
codes = set ()
for i in range ( 0 , len (string) - 1 ):
codes.add(string[i:i + 2 ])
return len (codes)
if __name__ = = "__main__" :
string = "UPUP"
print (countDistinctCode(string))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int countDistinctCode(String str)
{
HashSet<String> codes = new HashSet<String>();
for ( int i = 0; i < str.Length - 1; i++)
codes.Add(str.Substring(i,2));
return codes.Count;
}
public static void Main(String []args)
{
String str = "UPUP" ;
Console.Write(countDistinctCode(str));
}
}
|
Javascript
<script>
function countDistinctCode(str)
{
var codes = new Set();
for ( var i = 0; i < str.length - 1; i++)
codes.add(str.substr(i, 2));
return codes.size;
}
var str = "UPUP" ;
document.write(countDistinctCode(str))
</script>
|
Time Complexity: O(N)
Since we are traversing the given string of length N only once, the time complexity of the above algorithm is O(N).
Space Complexity: O(N)
The set used in the above algorithm is of size N and hence the space complexity of the algorithm is O(N).
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...