C++で文字列の最初に存在する繰り返し文字を検索します
文字列があるとします。繰り返される最初の文字を見つける必要があります。文字列は「HelloFriends」なので、最初に繰り返される文字はlになります。次々と2つのlがあるので。
これを解決するために、ハッシュ手法を使用します。ハッシュテーブルを1つ作成し、各文字を1つずつスキャンします。文字が存在しない場合はハッシュテーブルに挿入し、すでに存在する場合はその文字を返します。
例
#include<iostream>
#include<unordered_set>
using namespace std;
char getFirstRepeatingChar(string &s) {
unordered_set<char> hash;
for (int i=0; i<s.length(); i++) {
char c = s[i];
if (hash.find(c) != hash.end())
return c;
else
hash.insert(c);
}
return '\0';
}
int main () {
string str = "Hello Friends";
cout << "First repeating character is: " << getFirstRepeatingChar(str);
} 出力
First repeating character is: l
-
Javaで文字列の最初に繰り返される単語を検索する
Javaで文字列の最初に繰り返される単語を見つけるためのコードは、次のとおりです- 例 import java.util.*; public class Demo{ static char repeat_first(char my_str[]){ HashSet<Character> my_hash = new HashSet<>(); for (int i=0; i<=my_str.length-1; i++){
-
Pythonで文字列の最初に繰り返される単語を見つけますか?
1つの文字列が与えられます。私たちのタスクは、与えられた文字列の最初に繰り返される単語を見つけることです。この問題を実装するために、Pythonコレクションを使用しています。コレクションから、Counter()メソッドを取得できます。 アルゴリズム Repeatedword(n) /* n is the string */ Step 1: first split given string separated by space into words. Step 2: now convert the list of words into a dictionary. Step 3: travers