字符串数组中各字符串的最大公共子串的字典序

题目:给定一个仅由小写字母组成的字符串数组strArr,找出每个字符串都出现的字符,并将这些字符以字符串的形式按字典序输出,注意,若一个字符在字符串中多是出现,则需要多次输出

示例1:

输入:strArr={"smooth", "common", "mooorings"}

输出:“moo”

解释:m,o在每个字符串中都出现,m在"smooth"和"mooorings"中都出现了一次,在"common"中出现了2次,则公共元素m,出现了1次 ,公共元素o,出现了2次

 

示例2:

输入:strArr={"softwares"}

输出:“aeforsstw”

解释:只有一个字符串时,每个字符都是公共字符,所以直接对字符串按字典序输出就行

 

涉及知识点

  • 对字符串字典排序
public static void main(String[] args) {
        String s = "test";
        char[] ch = s.toCharArray();
        Arrays.sort(ch);
        s = new String(ch);
}

 

  • 统计字符串中每个字符出现的次数
public static int[] strInt(String s) {
        int[] count = new int[26];
        for (int i = 0; i < s.length(); ++i) {
            count[s.charAt(i) - 'a'] += 1;
        }
        return count;
}

 

本题求解:(没想到太好的方法,只想到这个O(n^2)的方法)

public class countChar {
    // 1、统计字符串中每个字符的频次(只包含小写字符)
    public static int[] strInt(String s) {
        int[] count = new int[26];
        for (int i = 0; i < s.length(); ++i) {
            count[s.charAt(i) - 'a'] += 1;
        }
        return count;
    }

    public static String countStr(String[] str) {
        int len = str.length;
        int[][] arr = new int[len][]; // 2、用一个len*26的数组记录每个字符串中每个字符出现的次数
        for (int i = 0; i < len; ++i) {
            arr[i] = strInt(str[i]);
        }
        StringBuffer bf = new StringBuffer(); // 3、创建一个bf存储公共字符
        for (int i = 0; i < 26; ++i) {
            int j = 0;
            int min = Integer.MAX_VALUE; // 4、记录公共字符在所有字符串中最大出现的次数
            for (j = 0; j < len; ++j) {
                if (arr[j][i] == 0) {
                    break;
                } else {
                    min = Math.min(min, arr[j][i]);
                }
            }
            if (j == len && min != Integer.MAX_VALUE) { // 说明所有的字符串都包含这个字符
                for (int g = 0; g < min; ++g) {
                    bf.append((char) ('a' + i)); // 5、将最大次数的公共字符加到bf中
                }
            }
        }
        // 6、由于本身就是按照字典序统计的,所以直接输出即可
return bf.toString();
 } 
}

 

posted @ 2022-07-19 20:55  Justin_Hu  阅读(133)  评论(0)    收藏  举报