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;
    }
}

class Solution {
    public int numberOfBeams(String[] bank) {
        int pre = 0;
        int result = 0;
        for (String b : bank) {
            int count = 0;
            for (char c : b.toCharArray()) {
                if (c == '1') {
                    count++;
                }
            }
            if (pre != 0 && count != 0) {
                result += pre*count;
            }
            if (pre == 0 || count != 0) {
                pre = count; // pre = 3
            }
        }
        return result;
    }
}

more simple

```java
class Solution {
    public int numberOfBeams(String[] bank) {
        int pre = 0;
        int result = 0;
        for (String b : bank) {
            int count = 0;
            for (char c : b.toCharArray()) {
                count += c - '0';
            }
            if (count == 0) {
                continue;
            }
            result += pre*count;
            pre = count; // pre = 3
        }
        return result;
    }
}
```

Last updated