1370. Increasing Decreasing String

本文介绍了一种新颖的字符串排序算法,通过反复前后遍历有序数组,先找最小再找最大,巧妙利用字典序降低排序复杂度。使用长度为26的数组作为桶,每个桶计数各字母数量,采用strings.Builder进行高效字符串拼接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1370. Increasing Decreasing String
Given a string s. You should re-order the string using the following algorithm:

Pick the smallest character from s and append it to the result.
Pick the smallest character from s which is greater than the last appended character to the result and append it.
Repeat step 2 until you cannot pick more characters.
Pick the largest character from s and append it to the result.
Pick the largest character from s which is smaller than the last appended character to the result and append it.
Repeat step 5 until you cannot pick more characters.
Repeat the steps from 1 to 6 until you pick all characters from s.
In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.

Return the result string after sorting s with 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.

Example 3:
Input: s = “leetcode”
Output: “cdelotee”

Example 4:
Input: s = “ggggggg”
Output: “ggggggg”

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/increasing-decreasing-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Think and method
Today’s problem is listed as a simple problem in Leetcode, but it can be seen that the problem itself is quite complex. Nevertheless, after sorting it out, we can actually summarize it as:

repeatedly traversing forward and backward through a well-arranged array, which can not only achieve the purpose of finding the minimum first and then finding the maximum.

In the previous two weeks, we found that sorting is usually a time-consuming process, but since we only need to deal with the letters in this case, we can easily use the dictionary order to reduce the complexity of sorting. A simple traversal can be done.At the same time, we have also used the method mentioned above, “bucket”, which uses an array of 26 lengths to represent 26 buckets. Each bucket contains one letter, and counts the number of each letter.

In this problem, I also learned to use a new way of string concatenation, which is easy to concatenate using strings.Builder and WriteByte, which greatly reduced the complexity of the actual code in this problem.

Specifically, the algorithm uses the previously set bucket to detect whether the current position of the bucket counts as a value of 0. If not, the current letter is added to the end of the string and the value of counter -1.

Time complexity: O(s) s is the length of string

Space complexity: O(26)

Code:

func sortString(s string) string {
    var result strings.Builder
    var buckets [26]byte

    //An array of length 26 represents 26 buckets
    for _, v := range s{
        buckets[v - 'a'] ++
    }

    length := len(s)
    //every time find buckets[i] > 0 
    //Add the letter corresponding to the bucket to the end of the result string

    for length > 0{
    //from small to big
        for i:= 0; i <= 25;i++{
            if buckets[i] > 0{
                result.WriteByte('a' + byte(i))
                buckets[i] --
                length --
            }
        }
    //from big to small
        for i:= 25; i >= 0;i--{
            if buckets[i] > 0{
                result.WriteByte('a' + byte(i))
                buckets[i] --
                length --
            }
        }
    }
    return result.String()
}

Test:
Example 1:
Input: s = “aaaabbbbcccc”
在这里插入图片描述

Example 2:
Input: s = “rat”
在这里插入图片描述

Example 3:
Input: s = “leetcode”
在这里插入图片描述

Example 4:
Input: s = “ggggggg”
在这里插入图片描述

/** * Verify focus distance control. * * Assumption: * - First repeatStart+1 elements of requestedDistances share the same value * - Last repeatEnd+1 elements of requestedDistances share the same value * - All elements in between are monotonically increasing/decreasing depending on ascendingOrder. * - Focuser is at requestedDistances[0] at the beginning of the test. * * @param requestedDistances The requested focus distances * @param resultDistances The result focus distances * @param lensStates The result lens states * @param ascendingOrder The order of the expected focus distance request/output * @param noOvershoot Assert that focus control doesn't overshoot the requested value * @param repeatStart The number of times the starting focus distance is repeated * @param repeatEnd The number of times the ending focus distance is repeated * @param errorMargin The error margin between request and result */ private void verifyFocusDistance(float[] requestedDistances, float[] resultDistances, int[] lensStates, boolean ascendingOrder, boolean noOvershoot, int repeatStart, int repeatEnd, float errorMargin) { float minValue = 0; float maxValue = mStaticInfo.getMinimumFocusDistanceChecked(); float hyperfocalDistance = 0; if (mStaticInfo.areKeysAvailable(CameraCharacteristics.LENS_INFO_HYPERFOCAL_DISTANCE)) { hyperfocalDistance = mStaticInfo.getHyperfocalDistanceChecked(); } // Verify lens and focus distance do not change for first repeatStart // results. for (int i = 0; i < repeatStart; i ++) { float marginMin = requestedDistances[i] * (1.0f - errorMargin); // HAL may choose to use hyperfocal distance for all distances between [0, hyperfocal]. float marginMax = Math.max(requestedDistances[i], hyperfocalDistance) * (1.0f + errorMargin); mCollector.expectEquals("Lens moves even though focus_distance didn't change", lensStates[i], CaptureResult.LENS_STATE_STATIONARY); if (noOvershoot) { mCollector.expectInRange("Focus distance in result should be close enough to " + "requested value", resultDistances[i], marginMin, marginMax); } mCollector.expectInRange("Result focus distance is out of range", resultDistances[i], minValue, maxValue); } for (int i = repeatStart; i < resultDistances.length-1; i ++) { float marginMin = requestedDistances[i] * (1.0f - errorMargin); // HAL may choose to use hyperfocal distance for all distances between [0, hyperfocal]. float marginMax = Math.max(requestedDistances[i], hyperfocalDistance) * (1.0f + errorMargin); if (noOvershoot) { // Result focus distance shouldn't overshoot the request boolean condition; if (ascendingOrder) { condition = resultDistances[i] <= marginMax; } else { condition = resultDistances[i] >= marginMin; } mCollector.expectTrue(String.format( "Lens shouldn't move past request focus distance. result " + resultDistances[i] + " vs target of " + (ascendingOrder ? marginMax : marginMin)), condition); } // Verify monotonically increased focus distance setting boolean condition; float compareDistance = resultDistances[i+1] - resultDistances[i]; if (i < resultDistances.length-1-repeatEnd) { condition = (ascendingOrder ? compareDistance > 0 : compareDistance < 0); } else { condition = (ascendingOrder ? compareDistance >= 0 : compareDistance <= 0); } mCollector.expectTrue(String.format("Adjacent [resultDistances, lens_state] results [" + resultDistances[i] + "," + lensStates[i] + "], [" + resultDistances[i+1] + "," + lensStates[i+1] + "] monotonicity is broken"), condition); } mCollector.expectTrue(String.format("All values of this array are equal: " + resultDistances[0] + " " + resultDistances[resultDistances.length-1]), resultDistances[0] != resultDistances[resultDistances.length-1]); // Verify lens moved to destination location. mCollector.expectInRange("Focus distance " + resultDistances[resultDistances.length-1] + " for minFocusDistance should be closed enough to requested value " + requestedDistances[requestedDistances.length-1], resultDistances[resultDistances.length-1], requestedDistances[requestedDistances.length-1] * (1.0f - errorMargin), requestedDistances[requestedDistances.length-1] * (1.0f + errorMargin)); }解释这个函数
07-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值