對“xAyB”形式的字串進行編碼,其中x和y基於數字的計數。


在這個問題中,我們需要將字串編碼為 xAyB 格式,其中 x 是兩個字串在相同索引處出現的數字計數,y 是兩個字串在不同索引處出現的數字計數。

我們可以透過計算兩個字串中相同的數字來解決這個問題。此外,我們可以計算兩個字串中在相同索引處出現的相同數字的總數來對字串進行編碼。

問題陳述 - 我們得到了兩個長度相同的字串 str1 和 str2,它們只包含數字。我們需要將給定的字串編碼為 xAyB 格式。這裡,A 和 B 是常量。

  • X 是在 str1 和 str2 中相同且存在於相同索引處的數字總數。

  • Y 是在 str1 和 str2 中相同但存在於不同索引處的數字總數。

示例

輸入

str1 = 4231, str2 = 4623

輸出

1A2B

解釋 - 在輸入字串中,“2”是公共數字,並且在兩個字串中的相同索引處存在。

在兩個字串中,“4”和“3”也是公共數字,它們存在於不同的索引處。

輸入

str1 = 1234, str2 = 1234

輸出

4A0B

解釋 - 在給定的字串中,所有字元都相同,並且存在於相同的索引處。因此,x 為 4,y 為 0。

輸入

str1 = 6543, str2 = 3456;

輸出

0A4B

解釋 - 給定的字串包含所有相同的字元,但存在於不同的索引處。因此,x 為 0,y 為 4。

方法 1

在這種方法中,我們將找到兩個字串中相同數字的計數。之後,我們將找到在相同索引處出現的相同數字的計數,並使用它來計算在不同索引處出現的相同數字的總數。

演算法

步驟 1 - 使用 toString() 方法將整數轉換為字串。

步驟 2 - 初始化大小為 10 且值為 0 的 freq1 和 freq2 列表,用於儲存 str1 和 str2 中數字的頻率。

步驟 3 - 逐個遍歷 str1 和 str2 來計算數字的頻率。

步驟 4 - 將 'sameDigits' 變數初始化為零,用於儲存兩個字串中相同數字的計數,並將 'sameIndex' 初始化為零,用於儲存在相同索引處出現的相同數字的計數。

步驟 5 - 進行 0 到 9 次迭代,並將 freq1[p] 和 freq2[p] 的最小值新增到 'sameDigits' 變數的值中。

步驟 6 - 現在,遍歷兩個字串,如果在兩個字串的第 p 個索引處任何字元相同,則將 'sameIndex' 的值增加 1。

步驟 7 - 從 sameDigits 中減去 sameIndex。

步驟 8 - 編碼字串。這裡,sameIndex 是 x 的值,sameDigits 是 y 的值。

步驟 9 - 返回編碼後的字串。

示例

#include <bits/stdc++.h>
using namespace std;

string getEncodedStr(int str1, int str2) {
   // Conver numeric strings to strings
   string temp1 = to_string(str1), temp2 = to_string(str2);
   // Calculate sameDigits of digits in str1
   vector<int> freq1(10, 0);
   for (char ch : temp1)
      freq1[ch - '0']++;
   // Calculate sameDigits of digits in str2
   vector<int> freq2(10, 0);
   for (char ch : temp2)
      freq2[ch - '0']++;
   int sameDigits = 0, sameIndex = 0;
   // Find the total number of counts of the same digits
   for (int p = 0; p < 10; p++)
      sameDigits += min(freq1[p], freq2[p]);
   // Find the total number of counts of the same digits on the same indices
   for (int p = 0; p < temp1.length() && temp2.length(); p++) {
      if (temp1[p] == temp2[p]) {
         sameIndex++;
      }
   }
   // Get the total number of the same digits on different indices
   sameDigits -= sameIndex;
   // Encode the string
   string ans = "" + to_string(sameIndex) + "A" + to_string(sameDigits) + "B";
   return ans;
}
int main() {
   int str1 = 4231, str2 = 4623;
   cout << "The encoded string is - " << getEncodedStr(str1, str2) << endl;
   return 0;
}

輸出

The encoded string is - 1A2B

時間複雜度 - O(N),用於遍歷字串和計數數字頻率。

空間複雜度 - O(1),因為我們使用常量空間來計算 10 個數字的頻率。

我們學習了透過計算在相同和不同索引處出現的相同數字來對字串進行編碼。程式設計師可以嘗試透過使用在相同或不同索引處出現的數字的和來對字串進行編碼。

更新於:2023年8月24日

49 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告