C++ 将一个字符串简化为最小长度的有效电子邮件地址,通过替换指定的子字符串
在这个问题中,我们给出了一个包含“dot”和“at”单词的电子邮件字符串。我们需要用“.”和“@”字符替换它们。
注意 – 有效的电子邮件地址应该只包含一个“@”字符。它应该包含“@”字符之前的任何前缀和之后的域名。此外,有效的电子邮件可以包含多个“.”字符。而且,“@”和“.”字符不能出现在电子邮件地址的开头和结尾。
问题陈述 - 我们给出了一个包含电子邮件地址的字符串str,字符串的长度等于N。我们需要通过用“@”字符替换“at”字符串和用“.”字符替换“dot”字符串来缩短字符串。
示例
输入 - str = “contactattutorialspointdotcom”
输出 - contact@tutorialspoint.com
解释 - 我们已经分别用’@’和’.’来替换了“at”和“dot”字符。
输入 - str = “atatgmaildotcom”
输出 - at@gmail.com
解释 - 电子邮件只能包含一个’@’,并且不能以它开头,所以输出如上所示。
方法1
在这种方法中,我们将检查电子邮件是否包含当前字符的子字符串’at’或’dot’。我们可以将它替换为’@’和’.’字符。
步骤
- 定义’len’变量并存储变量的长度。
- 定义’minStr’变量并用原始字符串的第一个字符进行初始化。
- 定义’I’变量,并初始化为1以便在循环中使用。同时,定义’isAtIncluded’变量,并初始化为false以跟踪字符串中是否包含了’@’字符。
- 开始使用循环迭代字符串。
- 如果I < len – 3,isAtIncluded的值为false,并且长度为2的子字符串等于’at’,则将’@’附加到’minStr’字符串。同时,将I增加1。
- 否则,如果I < len – 4,并且长度为3的子字符串等于’dot’,则将’.’字符附加到给定的字符串。同时,将I的值增加2。
- 否则,将当前字符附加到minStr字符串中。
- 返回minStr字符串的值。
示例
#include <iostream>
#include <iostream>
using namespace std;
// function to minimize the string by replacing at with @ and dot with '.'
string minifyEmail(string original){
string minstr = "";
int len = original.length();
// append the first character to the final string
minstr += original[0];
// start index
int i = 1;
// Check wether at(@) already included or not
bool isAtIncluded = false;
// travere the string
for (int i = 0; i < len; i++){
// at can be replaced at most once
if (i < len - 3 && !isAtIncluded && original.substr(i, 2) == "at"){
// add '@' to minstr
minstr += '@';
// Update isAtIncluded
isAtIncluded = true;
i++;
}
// If current substring found dot
else if (i < len - 4 && original.substr(i, 3) == "dot"){
// add '.' to minstr
minstr += '.';
i += 2;
} else {
minstr += original[i];
}
}
return minstr;
}
int main(){
string original = "contactattutorialspointdotcom";
cout << "The string after minifying in the proper original format is " << minifyEmail(original);
}
输出
The string after minifying in the proper original format is ccontact@tutorialspoint.com
时间复杂度 – O(N),因为我们遍历字符串。
空间复杂度 – O(N),因为我们存储了压缩后的字符串。
在上面的代码中,我们始终将第一个字符附加到minstr字符串。因此,它不会在开头添加’@’或’.’字符。此外,用户可以使用replace()方法将“点”替换为“.”,将“at”替换为“@”字符,但程序员需要确保它只会向字符串中添加一个单独的“@”字符。
极客笔记