透過替換指定的子字串,將字串簡化為最小長度的有效電子郵件地址。
在這個問題中,我們給出了包含“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() 方法將“dot”替換為“.”,將“at”替換為“@”字元,但程式設計師需要確保它只向字串新增一個“@”字元。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP