【Lintcode】1890. Form Minimum Number

题目地址:

https://www.lintcode.com/problem/form-minimum-number/description

给定一个只含 I I I D D D的长 n n n的字符串 s s s,题目保证 1 ≤ ∣ s ∣ ≤ 8 1\le |s|\le 8 1s8。要求返回一个含 1 ∼ 9 1\sim 9 19的长 n + 1 n+1 n+1字符串 t t t,使得 s [ i ] = I ⇔ t [ i + 1 ] > t [ i ] s[i]=I\Leftrightarrow t[i+1]>t[i] s[i]=It[i+1]>t[i],且 s [ i ] = D ⇔ t [ i + 1 ] < t [ i ] s[i]=D\Leftrightarrow t[i+1]<t[i] s[i]=Dt[i+1]<t[i]。返回符合要求的字典序最小的字符串。

思路是先把字符串 t = 12... n + 1 t=1 2 ... n + 1 t=12...n+1开出来,然后遍历 s s s,如果遇到 I I I则略过,如果遇到连续的 D D D,比如 s [ k : k + c ] = D s[k:k+c]=D s[k:k+c]=D,那么就将 t [ k : k + c + 1 ] t[k:k+c+1] t[k:k+c+1]翻转。举个例子。如果 s = D D I I D s=DDIID s=DDIID,那么先new出字符串 t = 123456 t=123456 t=123456,然后因为 s [ 0 : 1 ] = D s[0:1]=D s[0:1]=D,那么翻转 t [ 0 : 2 ] t[0:2] t[0:2],变为 321456 321456 321456,接着类似 s [ 4 : 4 ] = D s[4:4]=D s[4:4]=D,则翻转 t [ 4 : 5 ] t[4:5] t[4:5],变为 321465 321465 321465。最后所得字符串即为答案。算法正确性,先截取连续的 I I I,如果 s [ 0 : k ] = I s[0:k]=I s[0:k]=I,由于要字典序尽量小,所以 t t t的开头应该是 12... k + 1 12...k+1 12...k+1,接着如果遇到连续的 D D D,那么字典序最小应该是后面的若干数字反序,以此类推。代码如下:

public class Solution {
    /**
     * @param str: the pattern
     * @return: the minimum number
     */
    public String formMinimumNumber(String str) {
        // Write your code here.
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length() + 1; i++) {
            sb.append(i + 1);
        }
        
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == 'D') {
                int j = i;
                while (j < str.length() && str.charAt(j) == 'D') {
                    j++;
                }
                
                reverse(sb, i, j);
                
                i = j;
            }
        }
        
        return sb.toString();
    }
    
    // 翻转sb[i:j]
    private void reverse(StringBuilder sb, int i, int j) {
        for (; i < j; i++, j--) {
            char tmp = sb.charAt(i);
            sb.setCharAt(i, sb.charAt(j));
            sb.setCharAt(j, tmp);
        }
    }
}

时空复杂度 O ( n ) O(n) O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值