코딩응급실
프로그래머스: 크기가 작은 부분문자열 본문
바로 런타임 에러가 발생했다.
public class Solution {
public static void main(String[] args) {
String t = "500220839878"; // 숫자 문자열
String p = "7"; // <-- 얘 보다 작은 수들의 개수는?
Solution sol = new Solution();
int result = sol.solution(t, p);
System.out.println(result);
}
public int solution(String t, String p) {
int answer = 0;
int p_num = Integer.parseInt(p);
int t_len = t.length();
int p_len = p.length();
for (int x=0; x<t_len-p_len+1; x++) {
int num = Integer.parseInt(t.substring(x, x+p_len));
if (num <= p_num) {
answer++;
}
}
return answer;
}
}
그럼 어쩌라는 거지? 코드를 수정해보았지만...
public class Solution {
public static void main(String[] args) {
String t = "500220839878"; // 숫자 문자열
String p = "7"; // <-- 얘 보다 작은 수들의 개수는?
Solution sol = new Solution();
int result = sol.solution(t, p);
System.out.println(result);
}
public int solution(String t, String p) {
int answer = 0;
int p_num = Integer.parseInt(p);
int t_len = t.length();
int p_len = p.length();
for (int x = 0; x < t_len - p_len + 1; x++) {
String substring = t.substring(x, x + p_len);
/*
* 값이 0보다 작으면, 이는 substring이 p_num의 문자열 표현보다 앞에 오는 것을 의미합니다.
* 값이 0과 같으면, 이는 두 문자열이 동일하다는 것을 의미합니다.
* 값이 0보다 크면, 이는 substring이 p_num의 문자열 표현보다 뒤에 오는 것을 의미합니다.
*/
if (substring.compareTo(String.valueOf(p_num)) <= 0) {
answer++;
}
}
return answer;
}
}
이것도 런타임에러가 발생했다.
안되겠다.
문자열에 있는 t를 p의 길이만큼 반복하면서 문자열 p의 숫자 문자 하나씩 검사해보자.
public class Solution {
public static void main(String[] args) {
String t = "3141592"; // 숫자 문자열
String p = "271"; // <-- 얘 보다 작은 수들의 개수는?
Solution sol = new Solution();
int result = sol.solution(t, p);
System.out.println(result);
}
public int solution(String t, String p) {
int answer = 0;
int tLen = t.length();
int pLen = p.length();
for (int x = 0; x < tLen - pLen + 1; x++) {
if (isSmallerOrEqual(t, x, pLen, p)) {
answer++;
}
}
return answer;
}
private boolean isSmallerOrEqual(String t, int startIndex, int length, String p) {
// 문자열 t, 시작인덱스, p의 길이, 문자열 p
for (int i = 0; i < length; i++) {
char tChar = t.charAt(startIndex + i); //아하! p의 길이만큼 문자열 t에서 숫자를 하나씩 검사하네 !
char pChar = p.charAt(i); // 2, 7, 1
/*
*현재 비교하는 문자가 다르면,
*해당 문자의 아스키 코드 값을 비교하여 작은 것을 찾아냅니다.
*작은 문자열이 작은 숫자를 의미하므로 true를 반환합니다.
*/
if (tChar != pChar) {
return tChar < pChar;
}
}
return true; // 두 문자열이 동일한 경우도 포함
}
}
다행히 통과했다.
'Java' 카테고리의 다른 글
프로그래머스: 문자열 나누기 (0) | 2023.12.04 |
---|---|
프로그래머스: 가장 가까운 글자 (1) | 2023.12.04 |
프로그래머스: 개인정보 수집 유효기간 (1) | 2023.12.01 |
프로그래머스: 둘만의 암호 (0) | 2023.11.30 |
프로그래머스: 카드 뭉치 (0) | 2023.11.28 |