문자열 내 마음대로 정렬하기

문제 설명

문자열로 구성된 리스트 strings와, 정수 n이 주어졌을 때, 각 문자열의 인덱스 n번째 글자를 기준으로 오름차순 정렬하려 합니다. 예를 들어 strings가 [sun, bed, car]이고 n이 1이면 각 단어의 인덱스 1의 문자 u, e, a로 strings를 정렬합니다.

 

제한 조건

  • strings는 길이 1 이상, 50이하인 배열입니다.
  • strings의 원소는 소문자 알파벳으로 이루어져 있습니다.
  • strings의 원소는 길이 1 이상, 100이하인 문자열입니다.
  • 모든 strings의 원소의 길이는 n보다 큽니다.
  • 인덱스 1의 문자가 같은 문자열이 여럿 일 경우, 사전순으로 앞선 문자열이 앞쪽에 위치합니다.

 

입출력 예

strings n return
[sun, bed, car] 1 [car, bed, sun]
[abce, abcd, cdx] 2 [abcd, abce, cdx]

 

Python

Sorting How to?

 

Sorting HOW TO — Python 3.9.1 documentation

Sorting HOW TO Author Andrew Dalke and Raymond Hettinger Release 0.1 Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable. In this documen

docs.python.org

Python lambda

 

6. Expressions — Python 3.9.1 documentation

6. Expressions This chapter explains the meaning of the elements of expressions in Python. Syntax Notes: In this and the following chapters, extended BNF notation will be used to describe syntax, not lexical analysis. When (one alternative of) a syntax rul

docs.python.org

def solution(strings, n):
    strings.sort()
    strings.sort(key = lambda x : (x[n]))
    return strings

 

JavaScript

 

function solution(strings, n) {                 
    return strings.sort((a,b)=>{
        if(a[n] > b[n]){
            return 1;
        }
        if(a[n] < b[n]){
            return -1;
        }
        if(a[n] === b[n]){
            if(a > b) return 1;
            else if(a < b) return -1;
            else return 0;
        }
    })
}

 

C++

#include <string>
#include <vector>
#include <algorithm>
using namespace std;

vector<string> solution(vector<string> strings, int n) {
    int len = strings.size();

    for(int i=0; i<len; i++)
    {
       for(int j=i+1;j<=len-1;j++)
       {
           if(strings[i][n] > strings[j][n])
           {
               string temp = strings[i];
               strings[i] = strings[j];
               strings[j] = temp;
           }

           else if(strings[i][n] == strings[j][n])
           {
               if(strings[i]>strings[j])
                   strings[j].swap(strings[i]);
           }
       }
    }

    return strings;
}
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기