Efficient way to find Frequency of a character in a String in java : O(n)

前端 未结 5 600
野的像风
野的像风 2021-02-03 09:48

In a recent interview I was asked to write the below program. Find out the character whose frequency is minimum in the given String ? So I tried by iterating through the string

5条回答
  •  爱一瞬间的悲伤
    2021-02-03 10:44

    I think your approach is in theory the most efficient (O(n)). However in practice it needs quite a lot of memory, and is probably very slow.

    It is possibly more efficient (at least it uses less memory) to convert the string to a char array, sort the array, and then calculate the frequencies using a simple loop. However, in theory it is less efficient (O(n log n)) because of sorting (unless you use a more efficient sort algorithm).

    Test case:

    import java.util.Arrays;
    
    public class Test {
    
        public static void main(String... args) throws Exception {
            //        System.out.println(getLowFrequencyChar("x"));
            //        System.out.println(getLowFrequencyChar("bab"));
            //        System.out.println(getLowFrequencyChar("babaa"));
            for (int i = 0; i < 5; i++) {
                long start = System.currentTimeMillis();
                for (int j = 0; j < 1000000; j++) {
                    getLowFrequencyChar("long start = System.currentTimeMillis();");
                }
                System.out.println(System.currentTimeMillis() - start);
            }
    
        }
    
        private static char getLowFrequencyChar(String string) {
            int len = string.length();
            if (len == 0) {
                return 0;
            } else if (len == 1) {
                return string.charAt(0);
            }
            char[] chars = string.toCharArray();
            Arrays.sort(chars);
            int low = Integer.MAX_VALUE, f = 1;
            char last = chars[0], x = 0;
            for (int i = 1; i < len; i++) {
                char c = chars[i];
                if (c != last) {
                    if (f < low) {
                        if (f == 1) {
                            return last;
                        }
                        low = f;
                        x = last;
                    }
                    last = c;
                    f = 1;
                } else {
                    f++;
                }
            }
            if (f < low) {
                x = last;
            }
            return (char) x;
        }
    
    }
    

提交回复
热议问题