check number of a given character occurence in a String

后端 未结 6 880
天涯浪人
天涯浪人 2021-01-28 13:23

I want to write a simple class to process Strings (may be very long strings up to 1mil characters in it). String will basically consists of two characters \"a\" and \"b\" that

6条回答
  •  梦如初夏
    2021-01-28 13:46

    You should definitely not using regexp for this problem: generally speaking, regexp is not good when you need to count anything. You cannot even write a regexp to check if brackets in an expression are balanced.

    For this problem a simple counter will be sufficient: increment on a, decrement on b, check for zero in the end to know the answer to your problem.

    boolean check(String s) {
        int count = 0;
        for (int i = 0 ; i != s.length() ; i++) {
            if (s.charAt(i) == 'a') {
                count++;
            } else { /* it is b */
                count--;
            }
        }
        return count == 0;
    }
    

提交回复
热议问题