C++ 最左边出现的重复字符
介绍
在本教程中,我们将开发一种方法来找出字符串中最左边出现的重复字符。这意味着该字符首次出现在字符串的开头。为了找出第一个字符是否重复,我们遍历整个字符串,并将每个字符与字符串的第一个字符进行匹配。为了解决这个任务,我们使用了C++编程语言的find()、length()和end()函数。
示例1
String = “Tutorialspoint”
Output = The repeating character is “t”
在上面的示例中,输入字符串“tutorialspoint”的最左边的字符是“t”,并且这个字符在字符串中重复出现。
示例2
String = “abcaabb”
Output = The repeating character is “a”
在上面的示例中,“a”是输入字符串中最左边的字符,并且出现在字符串的其他部分。因此,输出为“a”。
示例3
String = “programming”
Output = No repeating character.
在上面的示例中,输入字符串的最左边的字符是“p”,在字符串中没有重复。因此,输出为没有重复的字符。 find() - 它是一个字符串类函数,返回子字符串中重复值的索引值。
语法
find(char)
- length() - 它是一个字符串类的函数,用于返回字符串的长度。
语法
string_name.length()
- end() − 这是一个库函数,它返回容器中最后一个元素的迭代器值。
步骤
- 输入一个字符串。
-
遍历整个字符串,并将其字符保存在unordered_map中。
-
将字符串的第一个字符与map中保存的字符进行比较。
-
检查是否有任何字符串字符与保存的字符匹配。
-
打印输出。
示例
为了编码上面列出的示例之一,我们使用C++中的蛮力方法将每个字符与输入字符串中的最左字符匹配。实现中使用的C++函数如下:
#include <iostream>
#include <unordered_map>
using namespace std;
char findLeftmostRepeatedChar(string s){
unordered_map<char, int> charMap;
// Traverse the string from left to right
for (int x = 0; x < s.length(); x++) {
char ch = s[x];
// If the character is already in the map, return it
if (charMap.find(ch) != charMap.end()) {
return ch;
} else {
// Otherwise, add the character to the map
charMap[ch] = x;
}
}
// If no character is repeated, return '\0'
return '\0';
}
int main() {
string s = "tutorialspoint";
char leftmostRepeatedChar = findLeftmostRepeatedChar(s);
if (leftmostRepeatedChar != '\0'){
cout << "The leftmost repeated character in "" << s << "" is '" << leftmostRepeatedChar << "'" << endl;
}
else{
cout << "There are no repeated characters in "" << s << """ << endl;
}
return 0;
}
输出
The leftmost repeated character in << s << is 't'
结论
在本文中,我们基于C++开发了一种寻找输入字符串中重复最左侧字符的方法。我们使用一些示例来解释任务的意义。对于其中一个示例的实现,我们使用了一些C++库函数。我们将给定字符串的第一个字符与字符串的所有剩余字符进行比较。