Четкие коды состояний, которые появляются в строке как непрерывные подстроки

Опубликовано: 23 Января, 2022

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

Input: str = “UPBRC” 
Output:
UP, PB, BR and RC are 4 different state codes that appear in string as contiguous sub-strings.
Input: str = “UPUP” 
Output:
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++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the count of
// distinct state codes
int countDistinctCode(string str)
{
    set<string> codes;
    for (int i = 0; i < str.length() - 1; i++)
 
        // Insert every sub-string
        // of length 2 in the set
        codes.insert(str.substr(i, 2));
 
    // Return the size of the set
    return codes.size();
}
 
// Driver code
int main()
{
    string str = "UPUP";
    cout << countDistinctCode(str);
 
    return 0;
}

Java

// Java implementation of the above approach.
import java.util.*;
 
class GFG
{
 
// Function to return the count of
// distinct state codes
static int countDistinctCode(String str)
{
    Set<String> codes = new HashSet<>();
    for (int i = 0; i < str.length() - 1; i++)
 
        // Insert every sub-String
        // of length 2 in the set
        codes.add(str.substring(i, i + 2));
 
    // Return the size of the set
    return codes.size();
}
 
// Driver code
public static void main(String[] args)
{
    String str = "UPUP";
    System.out.println(countDistinctCode(str));
}
}
 
// This code has been contributed by 29AjayKumar

Python3

# Python3 implementation of the approach
 
# Function to return the count of
# distinct state codes
def countDistinctCode(string):
 
    codes = set()
    for i in range(0, len(string) - 1):
 
        # Insert every sub-string
        # of length 2 in the set
        codes.add(string[i:i + 2])
 
    # Return the size of the set
    return len(codes)
 
# Driver code
if __name__ == "__main__":
 
    string = "UPUP"
    print(countDistinctCode(string))
 
# This code is contributed
# by Rituraj Jain

C#

// C# implementation of the above approach.
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Function to return the count of
// distinct state codes
static int countDistinctCode(String str)
{
    HashSet<String> codes = new HashSet<String>();
    for (int i = 0; i < str.Length - 1; i++)
 
        // Insert every sub-String
        // of length 2 in the set
        codes.Add(str.Substring(i,2));
 
    // Return the size of the set
    return codes.Count;
}
 
// Driver code
public static void Main(String []args)
{
    String str = "UPUP";
    Console.Write(countDistinctCode(str));
}
}
 
// This code has been contributed by Arnab Kundu

Javascript

<script>
// Javascipt implementation of the
// above approach
 
// Function to return the count of
// distinct state codes
function countDistinctCode(str)
{
    var codes = new Set();
    for (var i = 0; i < str.length - 1; i++)
   
        // Insert every sub-string
        // of length 2 in the set
        codes.add(str.substr(i, 2));
   
    // Return the size of the set
    return codes.size;
}
 
// Driver code
var str = "UPUP";
document.write(countDistinctCode(str))
 
// This code is contributed by ShubhamSingh10
</script>
Output: 

2