Каждый штат представлен строкой длины 2. Например, DL используется для Дели , HP для Химачал-Прадеша , UP для Уттар-Прадеша , PB для Пенджаба и т. Д.
Для данной строки str, состоящей только из прописных букв английского алфавита, задача состоит в том, чтобы найти количество различных кодов состояний, которые появляются в строке как непрерывные подстроки.
Примеры:
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.
Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.
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>
|