Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- hash table
- dynamic programming
- 코테
- string
- 코딩테스트
- Class
- simulation
- Math
- implement
- 자바
- Method
- Data Structure
- Number Theory
- 파이썬
- Stack
- bit manipulation
- Tree
- two pointers
- 구현
- Binary Tree
- greedy
- SQL
- geometry
- Matrix
- Binary Search
- database
- Counting
- java
- sorting
- array
Archives
- Today
- Total
코린이의 소소한 공부노트
[LeetCode/Easy] 696. Count Binary Substrings 본문
1. Input
1) String s
2. Output
1) s의 부분 문자열 중 0과 1의 개수가 같은 부분 문자열의 개수를 반환
- 이때 0은 0끼리, 1은 1끼리 붙어있어야 한다.
3. Constraint
1) 1 <= s.length <= 10^5
2) s는 0과 1로 이루어져 있다.
4. Example
Input: s = "00110011" -> Output: 6
Input: s = "10101" -> Output: 4
설명:
- “00110011”에서 조건을 만족하는 부분 문자열은 “0011”, “01”, “1100”, “10”, “0011”, “01”의 6개이다. 이때 “00110011”은 0은 0끼리, 1은 1끼리 있지 않기 때문에 조건을 만족하지 못한다.
- “10101”에서 조건을 만족하는 부분 문자열은 "10", "01", "10", "01"의 4개이다.
5. Code
1) 첫 코드(2023/05/29)
class Solution {
public int countBinarySubstrings(String s) {
int ans = 0;
List<Integer> list = new ArrayList<>();
for(int i=0 ; i<s.length() ; i++){
int j = i;
while(j<s.length() && s.charAt(j)==s.charAt(i)) j++;
list.add(j-i);
i = j-1;
}
for(int i=0 ; i<list.size()-1 ; i++)
ans += Math.min(list.get(i), list.get(i+1));
return ans;
}
}
- 5%, 5%...
2) 수정해본 코드(2023/05/29)
class Solution {
public int countBinarySubstrings(String s) {
int ans = 0, pre = 0;
for(int i=0 ; i<s.length() ; i++){
int j = i;
while(j<s.length() && s.charAt(j)==s.charAt(i)) j++;
if(pre>0)
ans += Math.min(pre, j-i);
pre = j-i;
i = j-1;
}
return ans;
}
}
- 16%, 7%로 그나마 나아졌다..ㅎ
'코딩테스트 풀이 > JAVA' 카테고리의 다른 글
[LeetCode/Easy] 700. Search in a Binary Search Tree (0) | 2023.05.30 |
---|---|
[LeetCode/Easy] 697. Degree of an Array (0) | 2023.05.29 |
[LeetCode/Easy] 671. Second Minimum Node In a Binary Tree (0) | 2023.05.29 |
[LeetCode/Easy] 661. Image Smoother (0) | 2023.05.29 |
[프로그래머스/Lv.0] x 사이의 개수 (0) | 2023.05.25 |