惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
人人都是产品经理
人人都是产品经理
IT之家
IT之家
T
The Blog of Author Tim Ferriss
V
V2EX
博客园 - 聂微东
The Cloudflare Blog
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
U
Unit 42
Vercel News
Vercel News
L
LangChain Blog
博客园 - 司徒正美
H
Help Net Security
Recent Announcements
Recent Announcements
Recorded Future
Recorded Future
V
Visual Studio Blog
Jina AI
Jina AI
Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
Y
Y Combinator Blog
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
J
Java Code Geeks
The Register - Security
The Register - Security
The GitHub Blog
The GitHub Blog
B
Blog RSS Feed
F
Fortinet All Blogs
B
Blog
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
云风的 BLOG
云风的 BLOG
爱范儿
爱范儿
MongoDB | Blog
MongoDB | Blog
F
Full Disclosure
有赞技术团队
有赞技术团队
罗磊的独立博客
博客园_首页
MyScale Blog
MyScale Blog
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium
Engineering at Meta
Engineering at Meta
量子位
I
InfoQ
小众软件
小众软件
P
Proofpoint News Feed

博客园 - Grandyang

[LeetCode] 1372. Longest ZigZag Path in a Binary Tree 二叉树中的最长交错路径 [LeetCode] 1371. Find the Longest Substring Containing Vowels in Even Counts 每个元音包含偶数次的最长子字符串 [LeetCode] 1368. Minimum Cost to Make at Least One Valid Path in a Grid 使网格图至少有一条有效路径的最小代价 [LeetCode] 1367. Linked List in Binary Tree 二叉树中的链表 [LeetCode] 1366. Rank Teams by Votes 通过投票对团队排名 [LeetCode] 1365. How Many Numbers Are Smaller Than the Current Number 有多少小于当前数字的数字 [LeetCode] 1363. Largest Multiple of Three 形成三的最大倍数 [LeetCode] 1362. Closest Divisors 最接近的因数 [LeetCode] 1361. Validate Binary Tree Nodes 验证二叉树 [LeetCode] 1360. Number of Days Between Two Dates 日期之间隔几天 [LeetCode] 1359. Count All Valid Pickup and Delivery Options 有效的快递序列数目 [LeetCode] 1358. Number of Substrings Containing All Three Characters 包含所有三种字符的子字符串数目 [LeetCode] 1357. Apply Discount Every n Orders 每隔n个顾客打折 [LeetCode] 1356. Sort Integers by The Number of 1 Bits 根据数字二进制下1 的数目排序 [LeetCode] 1354. Construct Target Array With Multiple Sums 多次求和构造目标数组 [LeetCode] 1353. Maximum Number of Events That Can Be Attended 最多可以参加的会议数目 [LeetCode] 1352. Product of the Last K Numbers 最后 K 个数的乘积 [LeetCode] 1351. Count Negative Numbers in a Sorted Matrix 统计有序矩阵中的负数 [LeetCode] 1349. Maximum Students Taking Exam 参加考试的最大学生数
[LeetCode] 1370. Increasing Decreasing String 上升下降字符串
Grandyang · 2025-01-18 · via 博客园 - Grandyang

You are given a string s. Reorder the string using the following algorithm:

  1. Remove the smallest character from s and append it to the result.
  2. Remove the smallest character from s that is greater than the last appended character, and append it to the result.
  3. Repeat step 2 until no more characters can be removed.
  4. Remove the largest character from s and append it to the result.
  5. Remove the largest character from s that is smaller than the last appended character, and append it to the result.
  6. Repeat step 5 until no more characters can be removed.
  7. Repeat steps 1 through 6 until all characters from s have been removed.

If the smallest or largest character appears more than once, you may choose any occurrence to append to the result.

Return the resulting string after reordering s using this algorithm.

Example 1:

Input: s = "aaaabbbbcccc"
Output: "abccbaabccba"
Explanation: After steps 1, 2 and 3 of the first iteration, result = "abc"
After steps 4, 5 and 6 of the first iteration, result = "abccba"
First iteration is done. Now s = "aabbcc" and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc"
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba"

Example 2:

Input: s = "rat"
Output: "art"
Explanation: The word "rat" becomes "art" after re-ordering it with the mentioned algorithm.

Constraints:

  • 1 <= s.length <= 500
  • s consists of only lowercase English letters.

这道题说是给了一个字符串s,让采取下面一系列的措施:

  1. 删除s中最小的字符并将其附加到结果中。
  2. 删除比上次附加的字符大的s中最小的字符,并将其附加到结果中。
  3. 重复步骤2,直到不能再删除任何字符。
  4. 删除s中最大的字符并将其附加到结果中。
  5. 删除比上次附加的字符小的s中最大的字符,并将其附加到结果中。
  6. 重复步骤5,直到不能再删除任何字符。
  7. 重复步骤1到6,直到所有字符从s中被删除。

那么实际上就是找每个状态下s中的最大或最小的字符以及其个数,所以就需要统计每个字符出现的次数,而且最好还要能很方便的知道最大最小的字符是什么。一般来说,如果只想统计每个字符出现的个数,会用 HashMap 来做,但是这道题明确说了需要知道最大和最小的字符,则就应该用 TreeMap 或者数组来做。这里用数组来做更方便一点,因为题目中限定了字符串s中只有 26 个小写字母,则用一个大小为 26 的数组来统计每个字母的出现次数即可,而遍历的方向就可以决定取最大或最小的字符。由于总体步骤是要循环执行的,所以最外层要套一个 while 循环,判定条件就是结果 res 的长度不等于原字符串s。

然后从头开始遍历统计字符个数的数组 charCnt,若某个字符个数自减1之后仍大于等于0,则说明该字符存在,并且是当前最大的字符,则将其加入结果 res 中,这样保证了每种字符只会取一个,这样一圈遍历下来步骤1至3就完成了。同理,从末尾往前遍历,若某个字符个数自减1之后仍大于等于0,则说明该字符存在,并且是当前最小的字符,则将其加入结果 res 中,这样保证了每种字符只会取一个,这样一圈遍历下来步骤4至6就完成了。同时最外层的循环保证了步骤1至6可以重复执行,最终循环退出后就得到符合要求的结果 res,参见代码如下:


class Solution {
public:
    string sortString(string s) {
        string res;
        vector<int> charCnt(26);
        for (char c : s) {
            ++charCnt[c - 'a'];
        }
        while (s.size() != res.size()) {
            for (int i = 0; i < 26; ++i) {
                if (--charCnt[i] >= 0) {
                    res += (i + 'a');
                }
            }
            for (int i = 25; i >= 0; --i) {
                if (--charCnt[i] >= 0) {
                    res += (i + 'a');
                }
            }
        }
        return res;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1370

参考资料:

https://leetcode.com/problems/increasing-decreasing-string

https://leetcode.com/problems/increasing-decreasing-string/solutions/533002/c-counts/

LeetCode All in One 题目讲解汇总(持续更新中...)