天天看点

[leetcode/lintcode 题解] 字节跳动面试真题:删除字符

描述

给定一个字符串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

继续阅读