题目地址:
https://www.lintcode.com/problem/min-deletions-to-obtain-string-in-right-format/description
给定一个字符串 s s s,只含 A A A和 B B B,要求从 s s s中删除若干字符,使得 s s s成为若干 A A A后面接若干 B B B的格式。问至少要删多少个字符。
我们可以枚举分割点,在该位置所有左边的 A A A和右边的 B B B予以保留,其余都删掉,然后看最少的删除方案。代码如下:
public class Solution {
/**
* @param s: the string
* @return: Min Deletions To Obtain String in Right Format
*/
public int minDeletionsToObtainStringInRightFormat(String s) {
// write your code here
if (s == null || s.isEmpty()) {
return 0;
}
int countA = 0, countB = 0;
// 先求一下总共多少个B
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'B') {
countB++;
}
}
// 枚举从最左端开始,后面所有的B都保留的情形
int res = s.length() - countB;
// 枚举s[i + 1 : ]的B都保留的情形
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'B') {
countB--;
} else {
countA++;
}
res = Math.min(res, s.length() - countA - countB);
}
return res;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。