문제 설명
문장 sentence에서 word가 몇 번째 단어와 일치하는지를 출력하는 프로그램을 구현하세요.
sentence에서 단어의 구분은 공백(" ")으로 구분하며, 단어는 0번째부터 시작합니다.
단, word가 sentence에 포함되지 않을 경우, -1를 출력하세요.
입력 형식
· sentence : 단어가 공백으로 구분된 문자열
· word : 찾고자 하는 단어 문자열
출력 형식
· word가 sentence에 몇 번째 단어와 일치하는지 정수로 반환
제약 사항
· 0 <= sentence.length <= 1000
· 0 <= word.length <= 1000
· sentence[i], word[i]는 알파벳 대소문자입니다.
입출력 형식
· 예시1
· 입력
· sentence = "Hello every world"
· word = "every"
· 출력 : 1
· 설명 : every는 두 번째 단어이므로, 답은 1이다. 0번째부터 센다는 것을 고려
· 예시2
· 입력
· sentence = "Hello every world"
· word = "ever"
· 출력 : -1
· 설명 : ever라는 단어는 sentence에 포함되어 있지 않으므로 -1이 출력이 된다.
정답 코드
class Solution {
public int solution(String sentence, String word) {
if (word.equals("")) {
return -1;
}
String[] words = sentence.split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word)) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
Solution st = new Solution();
String sentence = "Hello every world";
String word = "every";
String word2 = "ever";
System.out.println(st.solution(sentence, word));
System.out.println(st.solution(sentence, word2));
}
}
'연습 코딩테스트' 카테고리의 다른 글
연습문제 2-5(3) 마지막에 남은 카드 라이프 수치 (0) | 2023.04.08 |
---|---|
연습문제 2-5(2) 배열에서 n이 나타나는 가장 작은 인덱스 (0) | 2023.04.08 |
연습문제 2-4(5) 접두사가 되는 요소의 개수 (0) | 2023.04.08 |
연습문제 2-4(4) 조건을 만족하는 a, b의 쌍의 개수 (0) | 2023.04.08 |
연습문제 2-4(3) 문자열 회전에 의한 결과 판단 (0) | 2023.04.08 |