

* 문제 풀이
class Solution {
public int solution(String my_string, String is_prefix) {
int answer = 0;
int a = my_string.indexOf(is_prefix);
if(a == 0){
answer = 1;
}
return answer;
}
}
문자열 위치를 찾는 indexOf()를 사용해 my_string에서 is_prefix의 위치를 확인한다.
0이면 접두사이므로 1을 반환, -1이거나 다른 숫자라면 그대로 0을 반환한다.
* 프로그래머스 다른 풀이
class Solution {
public int solution(String my_string, String is_prefix) {
if (my_string.startsWith(is_prefix)) return 1;
return 0;
}
}
startsWith() 메서드를 사용해 접두사임을 확인
⨽ 대상 문자열이 특정 문자 또는 문자열로 시작되는지 확인하는 함수.
boolean 값(false/true)으로 리턴한다.
class Solution {
public int solution(String my_string, String is_prefix) {
int answer = 0;
int k=1;
String[] arr=new String[my_string.length()];
for(int i=0;i<my_string.length();i++){
arr[i]=my_string.substring(0,k);
k++;
}
for(int i=0;i<my_string.length();i++){
if(arr[i].equals(is_prefix)){
answer=1;
}
}
return answer;
}
}
'코테 > 프로그래머스 JAVA Lv.0' 카테고리의 다른 글
| [프로그래머스/java/Lv.0] 문자열의 앞의 n글자 (0) | 2025.03.05 |
|---|---|
| [프로그래머스/java/Lv.0] 카운트 업 (0) | 2025.02.24 |
| [프로그래머스/java/Lv.0] 배열 만들기 1 (0) | 2025.02.20 |
| [프로그래머스/java/Lv.0] 카운트 다운 (0) | 2025.02.20 |
| [프로그래머스/java/Lv.0] 첫 번째로 나오는 음수 (0) | 2025.02.19 |