1. split() 사용
import java.util.Scanner;
public class Main {
public String solution(String str) {
String answer=""; //문장에서 가장 긴 단어
int m = Integer.MIN_VALUE; //음수가 아니기에 0으로 초기화해도 됨
String[] s = str.split(" ");
for(String x : s){
int len=x.length();
if(len>m){
m=len;
answer =x;
}
}
return answer;
}
public static void main(String[] args){
Main T = new Main();
Scanner kb = new Scanner(System.in);
String str = kb.nextLine();
System.out.print(T.solution(str));
}
}
2. indexOf(), substring() 사용
import java.util.Scanner;
public class Main {
public String solution(String str) {
String answer=""; //문장에서 가장 긴 단어
int m = Integer.MIN_VALUE, pos; //음수가 아니기에 0으로 초기화해도 됨
while((pos=str.indexOf(' '))!=-1){ //띄어쓰기 발견 못하면 -1리턴, 발견하면 인덱스 번호 return
//첫번째 띄어쓰기 index->2
String tmp = str.substring(0, pos); //index 0부터 pos전까지
int len=tmp.length();
if (len > m) { //len>=m 하면 뒤 쪽 단어가 선택될 수 있음
m=len;
answer=tmp;
}
str=str.substring(pos + 1); //pos+1부터 끝까지 보냄
//pos는 It뒤의 띄어쓰기 부분 -> is~study까지로 str변경
//여기까지만 하면 마지막 단어인 study까지 못가고 time으로 결과가 나옴
}
//마지막 단어 처리
if(str.length()>m) answer=str; //마지막 단어의 길이가 m보다 크면 answer이 str로 바뀌어야함
return answer;
}
public static void main(String[] args){
Main T = new Main();
Scanner kb = new Scanner(System.in);
String str = kb.nextLine();
System.out.print(T.solution(str));
}
}
마지막 단어 처리하는 부분 주의!
'Algorithm > 문제' 카테고리의 다른 글
7. 회문 문자열 (0) | 2023.05.17 |
---|---|
6. 중복 문자 제거 (0) | 2023.05.16 |
5. 특정 문자 뒤집기 (0) | 2023.05.16 |
4. 단어 뒤집기 (0) | 2023.05.10 |
2.대소문자 변환 (0) | 2023.05.09 |