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

前端 未结 5 584
野的像风
野的像风 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:55

    I'd do it the following way as it involves the fewest lines of code:

    character you wish to want to know frequency of: "_"
    String "this_is_a_test"

    String testStr = "this_is_a_test";
    String[] parts = testStr.split("_"); //note you need to use regular expressions here
    int freq = parts.length -1;
    

    You may find weird things happen if the string starts or ends with the character in question, but I'll leave it to you to test for that.

提交回复
热议问题