LeetCode 1370. Ascending and descending strings

Give you a string s, please reconstruct the string according to the following algorithm:

Select the smallest character from s and connect it to the end of the result string.
Select the smallest character from the remaining characters in s, and the character is larger than the last added character, and it is appended to the result string.
Repeat step 2 until you can't select characters from s.
Select the largest character from s and connect it to the end of the result string.
Select the largest character from the remaining characters in s, and the character is smaller than the last added character, and it will be added to the result string.
Repeat step 5 until you can't select characters from s.
Repeat steps 1 to 6 until all characters in s have been selected.
In any step, if there is more than one minimum or maximum character, you can select any one of them and add it to the result string.

Please return the resulting string after reordering the characters in s.

1 <= s.length <= 500
s only contains lowercase English letters.

You can use a hash table to store the number of occurrences of each letter. In each loop, you can traverse the hash table twice from beginning to end and then from end to beginning to find the letters whose times are not 0 and add them to the result string:

class Solution {
    
    
public:
    string sortString(string s) {
    
    
        vector<int> hashtbl(26);

        for (char c : s) {
    
    
            ++hashtbl[c - 'a'];
        }

        string res;
        while (res.size() != s.size()) {
    
    
            for (int i = 0; i < hashtbl.size(); ++i) {
    
    
                if (hashtbl[i]) {
    
    
                    res += 'a' + i;
                    --hashtbl[i];
                }
            }

            for (int i = hashtbl.size() - 1; i >= 0; --i) {
    
    
                if (hashtbl[i]) {
    
    
                    res += 'a' + i;
                    --hashtbl[i];
                }
            }
        }

        return res;
    }
};

Guess you like

Origin blog.csdn.net/tus00000/article/details/112502666