C++での大文字小文字の順列
文字と数字の文字列があるとします。文字列に存在する文字の大文字と小文字のバージョンを使用して、その文字列のすべての可能な組み合わせを生成する必要があります。したがって、1つの文字列に数値しかない場合は、それだけが返されます。文字列が「1ab2」のようなものであるとすると、文字列は[「1ab2」、「1Ab2」、「1aB2」、「1AB2」]
になります。この問題を解決するために、再帰的アプローチを使用します。そのインデックスから作業を開始するには、インデックスパラメータが必要です。また、結果が作成されるまでの一時文字列も必要です。インデックスが文字列の長さと同じである場合は、一時文字列を返します。指定されたインデックスについて、それが小文字の場合は大文字にし、その逆も同様です。その後、再帰的にタスクを実行します。
例
理解を深めるために、次の実装を見てみましょう-
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<string> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
vector <string> res;
void solve(string s, int idx = 0, string temp = ""){
if(idx == s.size()){
res.push_back(temp);
return;
}
solve(s, idx + 1, temp + s[idx]);
int diff = 'a' - 'A';
if(s[idx] >= 'a' && s[idx] <= 'z'){
char x = (s[idx] - diff);
solve(s, idx + 1, temp + x);
}
else if (s[idx] >= 'A' && s[idx] <= 'Z'){
char x = (s[idx] + diff);
solve(s, idx + 1, temp + x);
}
}
vector<string> letterCasePermutation(string S) {
res.clear();
solve(S);
return res;
}
};
main(){
Solution ob;
print_vector(ob.letterCasePermutation("1ab2"));
print_vector(ob.letterCasePermutation("9876"));
} 入力
"1ab2" "9876"
出力
[1ab2, 1aB2, 1Ab2, 1AB2, ] [9876, ]
-
C++文字列を大文字に変換する
これはC++言語で文字列を大文字に変換するプログラムです 例 #include<iostream> #include<string.h> using namespace std; int main() { char s[30] = "This_is_string"; int i; for(i=0;i<=strlen(s);i++) { if(s[i]>=97 && s[i]<=122) { &n
-
C ++で文字列をトークン化しますか?
最初の方法は、文字列ストリームを使用して、スペースで区切られた単語を読み取ることです。これは少し制限されていますが、適切なチェックを提供すれば、タスクはかなりうまくいきます。 例 #include <vector> #include <string> #include <sstream> using namespace std; int main() { string str("Hello from the dark side"); string tmp; // A string