⭐문제 설명
어떤 문자열에 대해서 접두사는 특정 인덱스까지의 문자열을 의미합니다.
예를 들어, "banana"의 모든 접두사는 "b", "ba", "ban", "bana", "banan", "banana"입니다.
문자열 my_string 과 is_prefix 가 주어질 때, is_prefix 가 my_string 의 접두사라면 1을, 아니면 0을 return 하는 solution 함수를 작성해 주세요.
입출력 예
String my_string | String is_prefix | result |
"banana" | "ban" | 1 |
"banana" | "nan" | 0 |
"banana" | "abcd" | 0 |
"banana" | "bananan" | 0 |
⭐문제 풀이
내 풀이
class Solution {
public int solution(String my_string, String is_prefix) {
int answer = 0;
if(is_prefix.length()<=my_string.length()) {
if(my_string.substring(0,is_prefix.length()).equals(is_prefix)){
answer = 1;
}
}
return answer;
}
}
다른 사람 풀이
class Solution {
public int solution(String my_string, String is_prefix) {
if (my_string.startsWith(is_prefix)) return 1;
return 0;
}
}
⭐알게 된 정보
◆ startsWith()
String 클래스의 t startsWith() 메소드는 문자열이 특정 접두사로 시작하는지를 확인하는 데 사용된다.
문자열의 시작 부분이 주어진 접두사와 일치하는지 여부를 boolean 값으로 반환한다.
String str = "Hello, world!";
System.out.println(str.startsWith("Hello")); // true
System.out.println(str.startsWith("world")); // false
◆ endsWith()
String 클래스의 t startsWith() 메소드는 문자열이 특정 접미사로 시작하는지를 확인하는 데 사용된다.
문자열의 끝 부분이 주어진 접미사와 일치하는지 여부를 boolean 값으로 반환한다.
String str = "Hello, world!";
System.out.println(str.endsWith("Hello")); // false
System.out.println(str.endsWith("world!")); // true
'Backend > Java - Coding Test' 카테고리의 다른 글
[프로그래머스(Java)] Lv.1 문자열을 정수로 바꾸기 / Integer.parseInt() (0) | 2024.10.28 |
---|---|
[프로그래머스(Java)] Lv.0 리스트(배열) - n번째 원소부터 / Arrays.copyOfRange() (0) | 2024.09.12 |
[프로그래머스(Java)] Lv.0 연산 - 문자 리스트를 문자열로 변환하기 / String.join() (0) | 2024.09.11 |
[프로그래머스(Java)] Lv.0 연산 - 문자열 겹쳐쓰기 (0) | 2024.09.10 |
[프로그래머스(Java)] Lv.0 출력 - 홀짝 구분하기 (0) | 2024.09.10 |