[LeetCode] 3216. Lexicographically Smallest String After a Swap
Given a string s containing only digits, return the lexicographically smallest string that can be obtained after swapping adjacent digits in s with the same parity at most once.
Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.
Example 1:
Input: s = "45320"
Output: "43520"
Explanation:
s[1] == '5' and s[2] == '3' both have the same parity, and swapping them results in the lexicographically smallest string.
Example 2:
Input: s = "001"
Output: "001"
Explanation:
There is no need to perform a swap because s is already the lexicographically smallest.
Constraints:
2 <= s.length <= 100
s consists only of digits.
交换后字典序最小的字符串。
给你一个仅由数字组成的字符串 s,在最多交换一次 相邻 且具有相同 奇偶性 的数字后,返回可以得到的字典序最小的字符串。如果两个数字都是奇数或都是偶数,则它们具有相同的奇偶性。例如,5 和 9、2 和 4 奇偶性相同,而 6 和 9 奇偶性不同。
思路
注意交换的规则,两个数字只能同为奇数或者同为偶数才能互相交换。所以思路是从左往右遍历所有的字符,如果某两个相邻的字符 a 和 b (a 在左,b 在右)
具有相同的奇偶性且 a > b,则可以进行交换。照着这个思路,找到第一对符合条件的 a 和 b,即可交换并返回结果。为什么是第一对,是因为需要让字典序尽可能的小,你交换在后面的字符,字典序是不如交换第一对大的。
复杂度
时间O(n)
空间O(n)
代码
Java实现
class Solution { public String getSmallestString(String s) { int n = s.length(); char[] letters = s.toCharArray(); for (int i = 1; i < n; i++) { int a = letters[i - 1] - '0'; int b = letters[i] - '0'; if (helper(a, b) && a > b) { char temp = letters[i - 1]; letters[i - 1] = letters[i]; letters[i] = temp; return new String(letters); } } return s; } private boolean helper(int a, int b) { return a % 2 == b % 2; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
2020-10-30 [LeetCode] 724. Find Pivot Index
2020-10-30 [LeetCode] 1219. Path with Maximum Gold
2020-10-30 [LeetCode] 849. Maximize Distance to Closest Person
2019-10-30 [LeetCode] 374. Guess Number Higher or Lower
2019-10-30 [LeetCode] 35. Search Insert Position
2019-10-30 [LeetCode] 205. Isomorphic Strings
2019-10-30 [LeetCode] 87. Scramble String