📌  相关文章
📜  作为连续子字符串出现在字符串中的不同状态代码

📅  最后修改于: 2022-05-13 01:57:07.619000             🧑  作者: Mango

作为连续子字符串出现在字符串中的不同状态代码

每个州都由长度为 2 的字符串表示。例如, DL用于德里HP用于喜马偕尔邦UP用于北方邦PB用于旁遮普等。
给定一个仅由大写英文字母组成的字符串str ,任务是找出作为连续子字符串出现在字符串中的不同状态代码的数量。
例子:

方法:将每个长度为 2 的子字符串存储在一个集合中,最后返回集合的大小,这是在给定字符串中作为子字符串出现所需的不同状态代码的数量。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the count of
// distinct state codes
int countDistinctCode(string str)
{
    set 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 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 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,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


输出:
2