最左側字元首次出現時的重複字元
簡介
在本教程中,我們將開發一種方法來查詢字串中重複的字元,這些字元的首次出現位置是最左側。這意味著該字元首先出現在字串的開頭。為了找出第一個字元是否重複,我們遍歷整個字串並將每個字元與字串的第一個字元進行匹配。為了解決此任務,我們使用了 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() - 它是一個庫函式,返回最後一個容器元素的迭代器值。
演算法
選擇一個輸入字串。
遍歷整個字串並將字元儲存到無序對映中。
將字串的第一個字元與對映中儲存的字元進行比較。
檢查是否有任何字串字元與儲存的字元匹配。
列印輸出。
示例
要對上述列出的示例之一進行編碼,我們在 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++ 庫函式。我們將給定字串的第一個字元與字串的所有其餘字元進行比較。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP