【Weekly】No.185

C_01 重新格式化字符串

Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).

You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.

Return the reformatted string or return an empty string if it is impossible to reformat the string.

Input: s = "ab123"
Output: "1a2b3"

方法一:简化问题

其实不用说想的那么复杂,一个比较复杂的思路就是,

  • 先统计字符与字符下标。
  • 然后又通过比较数字与字母的个数,最后写一大堆 if else 控制谁先执行。

简化问题:

  • 默许数字 dig 最多,如果惟愿,则通过交换使得 dig 最多。
  • 然后通过先 append 类型数目较多的字符,后 append 类型数目较少的字符。
    • 但是需要满足一个条件:abs(dig.size() - alp.size() > 1,即两种类型的字符的数目差不大于 1
public String reformat(String s) {
    StringBuilder sb = new StringBuilder();
    ArrayList<Character> dig = new ArrayList<>(), alp = new ArrayList<>();
    char[] S = s.toCharArray();
    for (int i = 0; i < S.length; i++) {
        if (Character.isDigit(S[i])) dig.add(S[i]);
        else alp.add(S[i]);
    }
    if ( Math.abs(dig.size() - alp.size()) > 1)
        return "";

    if (dig.size() < alp.size()) {
        ArrayList<Character> t = dig;
        dig = alp;
        alp = t;
    }
    for (int i = 0; i < dig.size(); i++) {
        sb.append(dig.get(i));
        if (i < alp.size()) {
            sb.append(alp.get(i));
        }
    }
    return sb.toString();
}

复杂度分析

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( n ) O(n)

B_02 无

方法一:无


B_03 数青蛙

给你一个字符串 croakOfFrogs,它表示不同青蛙发出的蛙鸣声(字符串 “croak” )的组合。由于同一时间可以有多只青蛙呱呱作响,所以 croakOfFrogs 中会混合多个 “croak” 。请你返回模拟字符串中所有蛙鸣所需不同青蛙的最少数目。

注意:要想发出蛙鸣 “croak”,青蛙必须 依序 输出 ‘c’, ’r’, ’o’, ’a’, ’k’ 这 5 个字母。如果没有输出全部五个字母,那么它就不会发出声音。

如果字符串 croakOfFrogs 不是由若干有效的 “croak” 字符混合而成,请返回 -1 。

输入:croakOfFrogs = "crcoakroak"
输出:2 
解释:最少需要两只青蛙,“呱呱” 声用黑体标注
第一只青蛙 "crcoakroak"
第二只青蛙 "crcoakroak"

方法一:计数

  • 因为在合法的字符串中,每个字符的出现次数必定是相等的。
  • 如果存在字符次序不同,而且数量还大于相对顺序较前的字符,那么这个字符串是不合法的。
  • 在字符数量合法的情况下,需要的青蛙数量只取决于字符 c 与 k 的数量差。
    • 就比如:一只青蛙再叫的时候,同时有另一只青蛙也在叫,那么此时需要的青蛙数将会是 2。
public int minNumberOfFrogs(String croakOfFrogs) {
    int[] c = new int[5];
    char[] s = croakOfFrogs.toCharArray();
    int max = 0;
    for (char ch : s) {
        if (ch == 'c') c[0]++;
        if (ch == 'r') c[1]++;
        if (ch == 'o') c[2]++;
        if (ch == 'a') c[3]++;
        if (ch == 'k') c[4]++;
        for (int i = c.length-1; i >= 1; i--) {
            if (c[i] > c[i-1])
                return -1;
        }
        max = Math.max(max, c[0]-c[4]);
    }
    return c[0] == c[4] ? max : -1;
}

复杂度分析

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( 1 ) O(1)
发布了714 篇原创文章 · 获赞 199 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/105613074