题目地址:
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 1≤∣s∣≤8。要求返回一个含 1 ∼ 9 1\sim 9 1∼9的长 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]=I⇔t[i+1]>t[i],且 s [ i ] = D ⇔ t [ i + 1 ] < t [ i ] s[i]=D\Leftrightarrow t[i+1]<t[i] s[i]=D⇔t[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)。