C++ 字串排序並計算整數和


討論一個問題,將字母字串按排序順序重新排列,並新增字串中存在的所有整數,例如

Input : str = “adv4fc3”
Output : “ acdfv7”
Explanation: all the letters have been sorted to “acdfv” followed by the sum of integers 4 and 3.

Input: str = “ h2d7e3f ”
Output: “ defh12”
Explanation: all the letters have been sorted to “defh” followed by the sum of integers 2, 7, and 3.

解決方案方法

在這個問題中,我們需要執行兩個任務,一個是排序字串,另一個是新增整數。

  • 可以透過統計字串中每個字母出現的次數,然後根據其次數形成一個新字串來完成字串的排序。

  • 我們可以透過每次遇到整數時將其新增到一個變數中來進行整數的加法。

示例

上述方法的 C++ 程式碼

#include<bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
int main(){
    string str = "h2d7e3f";
        int ch[26] = {0};
    int count = 0;
    // traverse through all the characters of string.
    for (int i = 0; i < str.length(); i++){
        // keeping count of occurance every character.
        if (str[i]>='a' && str[i] <='z')
            ch[str[i] - 97] = ch[str[i] - 97] + 1;
        // If an Integer encounters.
        else
            count = count + (str[i]-'0');
    }
    string final = "";
    // Making a sorted string with the help of ch array.
    for (int i = 0; i < 26; i++){
        char a = (char)('a'+i);
        // insert the current character
        // to new string untill it count ends
        while (ch[i]-- != 0)
            final = final + a;
    }
   //  and finally insert sum of all integers in the string.
    if (count>0)
        final = final + to_string(count);
    cout << "Rearranged string: " << final;
    return 0;
}

輸出

Rearranged string: defh12

上述程式碼的解釋

  • 陣列 ch 初始化為大小 26,因為我們需要保留 26 個字母出現次數的計數。

  • 在第一個迴圈中,我們遍歷字串。對於每個字母,我們都會增加該字母的計數。對於每個整數,我們都會將其新增到 count 變數中。

  • 在第二個迴圈中,我們根據所有計數形成一個新的排序字串,其中我們根據其計數將字元附加到字串中。

  • 最後,我們將字串與我們在第一個迴圈中計算出的整數的總和附加在一起。

結論

在本教程中,我們討論瞭如何按排序順序排列字串,並根據雜湊表方法解決了一個基於此的問題。我們還討論了此問題的 C++ 程式碼。我們可以用其他任何程式語言(如 C、Java、Python 等)編寫。希望本教程對您有所幫助。

更新於: 2021年11月26日

803 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告