programmers

[프로그래머스] 배열 원소의 길이

대장형아 2023. 11. 19. 13:02

 

파이썬 풀이

def solution(strlist):
    answer = []
    for i in strlist:
        answer.append(len(i))
    
    return answer

 

strlist 값을 for문에 넣어주었다. answer에 len(i) 값을  append 하면 간단하게 완성된다. 

 

자바 풀이

class Solution {
    public int[] solution(String[] strlist) {
        int[] answer = new int [strlist.length];
        
        int length = strlist.length;
        for (int i=0; i<length; i++){
            answer[i] = strlist[i].length();
        }
        return answer;
    }
}

 

answer 에 길이는 입력되는 strlist의 길이와 동일하므로 answer = new int [strlist.length];으로 선언한다. 

그리고 리턴 시켜보면 

 

테스트 1은 [0,0,0,0] , 테스트 2는 [0,0,0] 이 출력된다. 

 

for문과 length() 메소드를 사용해서 answer [ i ] 의 값에 strlist[ i ] 의 길이를 넣어준다. 

 

length() 메소드 

문자열에서 문자의 개수를 얻을 수 있다.