串的习题2
1.1108. IP 地址无效化 - 力扣(LeetCode)
class Solution {
public:
string defangIPaddr(string address) {
string s="";
for(int i =0;i<address.size();++i){
if(address[i]=='.'){
s=s+"[.]";
}else s=s+address[i];
}
return s;
}
};
class Solution {
public:
int countAsterisks(string s) {
int sh = 0;//用来判断|出现奇数次还是偶数次
int ret = 0;
for(int i =0;i<s.size();++i){
if(s[i] == '|'){
sh = sh+1;
}else if(s[i]=='*'){
if(sh%2==0){//出现偶数次 需计数
ret++;
}
}
}
return ret;
}
};
3.1221. 分割平衡字符串 - 力扣(LeetCode)
class Solution {
public://贪心思路
int balancedStringSplit(string s) {
int cnt = 0;
int ret = 0;
for(int i =0;i<s.size();++i){
if(s[i] == 'L'){
++cnt;
}else {
--cnt;
}
if(cnt ==0){
ret++;
}
}
return ret;
}
};
4.LCR 182. 动态口令 - 力扣(LeetCode)
class Solution {
public:
string dynamicPassword(string password, int target) {
string ret;
int n = password.size();
for(int i =0;i<n;++i){
ret = ret + password[(i+target)%n];
}
return ret;
}
};
//123
//231
//312
//循环节就是字符串的长度 看作环 用取模来计算
5.1678. 设计 Goal 解析器 - 力扣(LeetCode)
class Solution {
public:
string interpret(string command) {
string ret = "";
for(int i = 0;i<command.size();++i){
if(command[i]=='G'){
ret = ret+'G';
}else if(command[i]=='('){
if(command[i+1]==')'){
ret = ret+'o';
i++;
}else if(command[i+1]=='a'){
ret = ret+"al";
i = i+3;//多走几步
}
}else{
ret = ret +'/';
}
}
return ret;
}
};
6.2114. 句子中的最多单词数 - 力扣(LeetCode)
class Solution {
public:
int mostWordsFound(vector<string>& sentences) {
int ret = 0;
for(int i = 0;i<sentences.size();++i){
int k = 1;
for(int j = 0;j<sentences[i].size();++j){
if(sentences[i][j] == ' '){
++k;
}
}
ret = max(ret,k);
}
return ret;
}
};
7.1684. 统计一致字符串的数目 - 力扣(LeetCode)
class Solution {
public:
int countConsistentStrings(string allowed, vector<string>& words) {
int has[256] = {0};
for(int i = 0;i<allowed.size();++i){
has[allowed[i]] = 1;
}
int sum = 0;
for(int i = 0;i<words.size();++i){
bool bfind = true;
for(int j = 0;j<words[i].size();++j){
char c = words[i][j];
if(has[c] == 0){
bfind = false;
break;
}
}
if(bfind){
++sum;
}
}
return sum;
}
};//哈希思想