计算给定字符串中唯一字符的数量
给定一个由小写英文字母组成的字符串str ,任务是找出字符串中存在的唯一字符的数量。
例子:
Input: str = “geeksforgeeks”
Output: 7
Explanation: The given string “geeksforgeeks” contains 7 unique characters {‘g’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’}.
Input: str = “madam”
Output: 3
方法:给定的问题可以使用集合数据结构来解决。这个想法是初始化一个存储给定字符串的所有不同字符的无序集。遍历字符串后的集合大小就是必填答案。
下面是上述方法的实现:
C++
// C++ program of the above approach
#include
using namespace std;
// Program to count the number of
// unique characters in a string
int cntDistinct(string str)
{
// Set to store unique characters
// in the given string
unordered_set s;
// Loop to traverse the string
for (int i = 0; i < str.size(); i++) {
// Insert current character
// into the set
s.insert(str[i]);
}
// Return Answer
return s.size();
}
// Driver Code
int main()
{
string str = "geeksforgeeks";
cout << cntDistinct(str);
return 0;
}
Java
// Java program of the above approach
import java.util.*;
class GFG{
// Program to count the number of
// unique characters in a string
static int cntDistinct(String str)
{
// Set to store unique characters
// in the given string
HashSet s = new HashSet();
// Loop to traverse the string
for(int i = 0; i < str.length(); i++)
{
// Insert current character
// into the set
s.add(str.charAt(i));
}
// Return Answer
return s.size();
}
// Driver Code
public static void main(String args[])
{
String str = "geeksforgeeks";
System.out.print(cntDistinct(str));
}
}
// This code is contributed by sanjoy_62
Python3
# Python 3 program of the above approach
# Program to count the number of
# unique characters in a string
def cntDistinct(st):
# Set to store unique characters
# in the given string
s = set([])
# Loop to traverse the string
for i in range(len(st)):
# Insert current character
# into the set
s.add(st[i])
# Return Answer
return len(s)
# Driver Code
if __name__ == "__main__":
st = "geeksforgeeks"
print(cntDistinct(st))
# This code is contributed by ukasp.
C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Program to count the number of
// unique characters in a string
static int cntDistinct(string str)
{
// Set to store unique characters
// in the given string
HashSet s = new HashSet();
// Loop to traverse the string
for(int i = 0; i < str.Length; i++)
{
// Insert current character
// into the set
s.Add(str[i]);
}
// Return Answer
return s.Count;
}
// Driver Code
public static void Main()
{
string str = "geeksforgeeks";
Console.Write(cntDistinct(str));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
7
时间复杂度: O(N)
辅助空间: O(1)