코딩테스트 풀이/JAVA
[LeetCode/Easy] 1869. Longer Contiguous Segments of Ones than Zeros
무지맘
2023. 6. 20. 23:35
1. Input
1) String s
2. Output
1) s에 있는 연속된 1의 개수 a와 연속된 0의 개수 b를 모두 세어 찾은 후, 가장 큰 a가 가장 큰 b보다 크면 true, 작거나 같으면 false를 반환
3. Constraint
1) 1 <= s.length <= 100
2) s는 0 또는 1로 이루어진 문자열이다.
4. Example
Input: s = "1101" -> Output: true
Input: s = "111000" -> Output: false
설명:
- 가장 큰 a=2 > 가장 큰 b=1 이므로 true
- 가장 큰 a=3 == 가장 큰 b=3 이므로 false
5. Code
1) 첫 코드(2023/06/20)
class Solution {
public boolean checkZeroOnes(String s) {
int i = 0, ones = 0, zeros = 0;
while(i<s.length()){
int j = i+1;
if(s.charAt(i)=='1'){
while(j<s.length() && s.charAt(j)=='1') j++;
if(j-i>ones)
ones = j-i;
} else{
while(j<s.length() && s.charAt(j)=='0') j++;
if(j-i>zeros)
zeros = j-i;
}
i = j;
}
return ones>zeros;
}
}
- 77%, 56%