首页  >  文章  >  后端开发  >  将字符串缩减为有效的最小长度电子邮件地址,通过替换指定的子字符串

将字符串缩减为有效的最小长度电子邮件地址,通过替换指定的子字符串

PHPz
PHPz转载
2023-09-06 11:01:06533浏览

将字符串缩减为有效的最小长度电子邮件地址,通过替换指定的子字符串

在这个问题中,我们给出了包含“dot”和“at”单词的电子邮件字符串。我们需要用“.”和“@”字符替换它们。

注意 - 有效的电子邮件地址应该只包含一个'@'字符。它应该包含'@'字符之前的任何前缀和之后的域名。此外,有效的电子邮件可以包含多个'.'字符。此外,'@'和'.'字符不应该位于电子邮件地址的开头或结尾。

问题陈述  给定一个包含电子邮件地址的字符串str,字符串的长度为N。我们需要通过将字符串中的“at”替换为“@”字符和“dot”替换为“.”字符来缩短字符串。

示例

输入-str=“contactattutorialspointdotcom”

输出– contact@tutorialspoint.com

说明 - 我们分别用“@”和“.”字符替换了“at”和点。

输入 – str = “atatgmaildotcom”

输出– at@gmail.com

说明– 电子邮件只能包含一个“@”,并且不能在开头包含它,因此输出如上所示

方法一

在这种方法中,我们将检查电子邮件是否包含当前字符的子字符串“at”或“dot”。我们可以用“@”和“.”字符替换它。

算法

  • 定义变量 'len' 并存储变量的长度。

  • 定义变量‘minStr’,并将其初始化为原始字符串的第一个字符

  • 定义‘I’变量,并将其初始化为1,以便在循环中使用。同时,定义‘isAtIncluded’变量并将其初始化为false,以跟踪字符串中的‘@’字符是否已经包含一次。

  • 开始使用循环迭代字符串。

  • 如果我

  • 否则,如果 I

  • 否则将当前字符附加到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”替换为“@”字符,但程序员需要确保它只会添加单个“@”字符字符串。

以上是将字符串缩减为有效的最小长度电子邮件地址,通过替换指定的子字符串的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除