2125. Number of Laser Beams in a Bank

count 1's number

T: O(n)

S: O(n)

class Solution {
    public int numberOfBeams(String[] bank) {
        int n = bank.length;
        int[] oneCount = new int[n];
        for (int i = 0; i < n; i++) {
            int count = (int)bank[i].chars().filter(ch -> ch == '1').count();
            oneCount[i] = count;
        }
        
        int res = 0;
        int prev = oneCount[0];
        for (int i = 1; i < n; i++) {
            if (oneCount[i] != 0) {
                res += prev*oneCount[i];
                prev = oneCount[i];
            }
        }
        return res;
    }
}

more simple

Last updated

Was this helpful?