描述
給定一個字元串str,現在要對該字元串進行删除操作,保留字元串中的k個字元且相對位置不變,并且使它的字典序最小,傳回這個子串。
線上評測位址:
領扣題庫官網樣例1
輸入:str="fskacsbi",k=2
輸出:"ab"
解釋:“ab“是str中長度為2并且字典序最小的子串
樣例2
輸入:str="fsakbacsi",k=3
輸出:"aac"
源代碼
public class Solution {
/**
* @param str: the string
* @param k: the length
* @return: the substring with the smallest lexicographic order
*/
public String deleteChar(String str, int k) {
int n = str.length();
char[] result = new char[k];
for (int i = 0; i < k; i ++) {
result[i] = str.charAt(n - k + i);
}
for (int i = n - k - 1; i >= 0; i --) {
char currentChar = str.charAt(i);
for (int j = 0; j < k; j ++) {
if (result[j] < currentChar) {
break;
} else {
char temp = result[j];
result[j] = currentChar;
currentChar = temp;
}
}
}
return String.valueOf(result);
}
}
更多題解參考:
九章官網solution