首頁 > 後端開發 > C++ > 主體

將字串縮減為有效的最小長度電子郵件地址,透過替換指定的子字串

PHPz
發布: 2023-09-06 11:01:06
轉載
470 人瀏覽過

將字串縮減為有效的最小長度電子郵件地址,透過替換指定的子字串

在這個問題中,我們給了包含「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 
#include 
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
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!