반응형

피드백

웬만한 함수 안 보고 할 수 있을 정도로 외워두어야 한다. 레퍼런스 주더라도 그거 보면 시간이 부족하다.

필수적으로 외워야 하는 함수들은 많이 풀면서 머릿속에 익히는 수밖에 없다.

한 300문제 정도 풀면 감이 잡힐 것

모든 문제는 for문과 if문으로 다 구현 가능하긴 하다.

풀고 나서 남들이 어떻게 풀었는지 참고

 

 

문제 링크

https://programmers.co.kr/learn/courses/30/lessons/72410

 

코딩테스트 연습 - 신규 아이디 추천

카카오에 입사한 신입 개발자 네오는 "카카오계정개발팀"에 배치되어, 카카오 서비스에 가입하는 유저들의 아이디를 생성하는 업무를 담당하게 되었습니다. "네오"에게 주어진 첫 업무는 새로

programmers.co.kr

 

나의 풀이

class Solution {
    public String solution(String new_id) {
        /*
        1. 아이디를 받아온다.
        2. toLowerCase로 1단계 구현한다.
        3. for 또는 regex로 문자열 치환
        여기서 어려움
        4. while 문 사용하여 3단계 구현
        5. if문과 indexOf()로 4단계 구현
        6. if문으로 5단계 구현
        7. subString으로 6단계 구현
        7.1. 4단계 실행
        8. for문으로 7단계 구현
        */

        // 1. 아이디를 받아온다.
        // 2. toLowerCase로 1단계 구현한다.
        new_id = new_id.toLowerCase();

        // 3. for 또는 regex로 문자열 치환   
        // while 문으로 대체
        String pattern = "[\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\=\\+\\\\\\[\\{\\]\\}\\:\\?\\,\\<\\>\\/]";
        //String pattern = "[.]";
        new_id = new_id.replaceAll(pattern, "");

        // 4. while 문 사용하여 3단계 구현
        // 정규식에서 +로 여러 문자열 한번에 검색 가능
        pattern = "\\.+";
        new_id = new_id.replaceAll(pattern, ".");

        // 5. if문과 indexOf()로 4단계 구현
        // ""는 string, ''는 char
        // StringBuilder 이 있어야 delete, deleteCharAt 가능
        if(new_id.charAt(0) == '.'){
            new_id = new_id.substring(1);
        }
        //길이가 0인 경우 제외 후 마지막 인덱스 확인
        if(new_id.length() != 0 && new_id.charAt(new_id.length()-1) == '.'){
            new_id = new_id.substring(0,new_id.length()-1);
        }

        // 6. if문으로 5단계 구현
        if(new_id.length() == 0){
            new_id = "a";
        }
        // 7. subString으로 6단계 구현
        if(new_id.length() > 15)
        new_id = new_id.substring(0, 15);
        // 7.1. 4단계 실행
        //길이가 0인 경우 제외 후 마지막 인덱스 확인
        if(new_id.length() != 0 && new_id.charAt(new_id.length()-1) == '.'){
            new_id = new_id.substring(0,new_id.length()-1);
        }

        // 8. for문으로 7단계 구현
        while(new_id.length() < 3){
            new_id = new_id + new_id.charAt(new_id.length()-1);
        }

        String answer = new_id;
        return answer;
    }
}

 

설계과정

1. 풀이 계획부터 세워야 한다. 코딩은 얼마 안 걸리니까.

 

1단계 new_id의 모든 대문자를 대응되는 소문자로 치환합니다.

2단계 new_id에서 알파벳 소문자, 숫자, 빼기(-), 밑줄(_), 마침표(.)를 제외한 모든 문자를 제거합니다.

3단계 new_id에서 마침표(.)가 2번 이상 연속된 부분을 하나의 마침표(.)로 치환합니다.

4단계 new_id에서 마침표(.)가 처음이나 끝에 위치한다면 제거합니다.

5단계 new_id가 빈 문자열이라면, new_id에 "a"를 대입합니다.

6단계 new_id의 길이가 16자 이상이면, new_id의 첫 15개의 문자를 제외한 나머지 문자들을 모두 제거합니다. 만약 제거 후 마침표(.)가 new_id의 끝에 위치한다면 끝에 위치한 마침표(.) 문자를 제거합니다.

7단계 new_id의 길이가 2자 이하라면, new_id의 마지막 문자를 new_id의 길이가 3이 될 때까지 반복해서 끝에 붙입니다.

 

나의 풀이 설계

1. 아이디를 받아온다.

2. toLowerCase로 1단계 구현한다.

3. for 또는 regex로 문자열 치환하여 2단계 구현한다.

4. while 문 사용하여 3단계 구현

5. if문과 indexOf()로 4단계 구현

6. if문으로 5단계 구현

7. subString으로 6단계 구현

7.1. 4단계 실행

8. for문으로 7단계 구현

 

함수의 구현을 요구하는 문제이다.

함수를 아는가? 모른다. 문자열 다루는 함수를 찾아보자.

필요한 함수

  • 대문자 소문자 변환 함수
  • 특수문자 제거를 위한 regex 함수(for문 대체 가능)
  • 문자열의 특정 위치(맨앞, 맨끝) 확인 함수(for문 대체 가능)
  • 특정 문자열 추출 함수
  • 문자열 세는 함수(for문 대체 가능)

  • 대문자 소문자 변환 함수

String의

대문자 변환: .toUpperCase()

소문자 변환: .toLowerCase()

문자열 일치 확인(java 는 대소문자 가림): .equals(foo)

대소문자 무시 문자열 일치 확인: .equalsIgnoreCase(foo)

출처: https://coding-factory.tistory.com/533

  • 특수문자 제거를 위한 regex 함수(for문 대체 가능)

Metacharacters

Regular Expression Description
. 어떤 문자 1개를 의미
^regex ^ 다음 regex로 line을 시작하는지
regex$ $ 앞의 regex가 line의 마지막으로 끝나는지
[abc] a, b, c 중의 문자 1개
[abc][vz] a, b, c 중에 문자 1개와 v, z 중에 문자 1개의 조합
[^abc] a, b, c를 제외한 문자 1개
[a-d1-7] ad, 17 사이의 문자 1개
X|Z X 또는 Z
\d 0~9 사이의 숫자, [0-9]와 동일
\D 숫자가 아닌 어떤 문자, [^0-9]와 동일
\s whitespace 1개, [\t\n\x0b\r\f]와 동일
\S whitespace를 제외한 문자
\w Alphanumeric(alphabet, 숫자) 문자, [a-zA-Z_0-9]와 동일
\W Alphanumeric을 제외한 문자(whitespace 등)
\S+ whitespace를 제외한 여러 문자
\b 단어의 경계(공백)를 찾습니다

 

Quantifiers

Regular Expression Description
* 0회 이상 반복
+ 1회 이상 반복
? 0 또는 1회만
{X} X회 이상 반복
{X,Y} X~Y 사이의 수만큼 반복
*? 가장 적게 일치하는 패턴을 찾음

 

Regex를 지원하는 String 메소드

String 클래스는 Regex를 지원하는 메소드들이 있습니다.

Method Description
String.matches(regex) String이 regex와 일치하면 true 리턴
String.split(regex) regex와 일치하는 것을 기준으로 String을 분리하여 배열로 리턴
String.replaceFirst(regex, replacement) regex와 가장 먼저 일치하는 것을 replacement로 변환
String.replaceAll(regex, replacement) regex와 일치하는 모든 것을 replacement로 변환
    예제
@Test
public void ex9() {
    String pattern = "a*[0-9]*";
    assertTrue("aaa123".matches(pattern));

    pattern = "\\s";
    String arr[] = "Hello World Java Regex".split(pattern);
    System.out.println(Arrays.asList(arr));

    pattern = "Hello";
    System.out.println("Hello World Hello World ".replaceFirst(pattern, "Regex"));

    pattern = "Hello";
    System.out.println("Hello World Hello World ".replaceAll(pattern, "Regex"));
}

 

결과

[Hello, World, Java, Regex]
Regex World Hello World
Regex World Regex World

출처: https://codechacha.com/ko/java-regex/

 

  • 문자열의 특정 위치(맨앞, 맨끝) 확인 함수(for문 대체 가능)

charAt

public char charAt​(int index)

 

Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing. If the char value specified by the index is a surrogate, the surrogate value is returned.

index에 해당하는 문자를 반환한다. 인덱스는 0부터 length()-1 까지이다. 첫 번째 문자 인덱스는 0이다.

만약 인덱스가 가리키는 문자열이 서로게이트라면, 서로게이트 값이 리턴된다.

 

Specified by:
charAt in interface CharSequence
Parameters:
index - the index of the char value.
Returns:
the char value at the specified index of this string. The first char value is at index 0.
Throws:
IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.

 

  • 특정 문자열 추출 함수

public String substring​(int beginIndex)

Returns a string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

해당 문자열의 하위 문자열을 반환한다. 하위 문자열은 매개변수 인덱스가 가리키는 문자부터 문자열의 마지막까지를 반환한다.

 

Examples:

    "unhappy".substring(2) returns "happy"

    "Harbison".substring(3) returns "bison"

    "emptiness".substring(9) returns "" (an empty string)

 

Parameters:

beginIndex - the beginning index, inclusive.

 

Returns:

the specified substring.

 

Throws:

IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.

 

public String substring​(int beginIndex, int endIndex)

Returns a string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

해당 문자열의 하위 문자열을 반환한다. 하위 문자열은 매개변수 시작 인덱스가 가리키는 문자부터 [매개변수 마지막 인덱스 - 1]이 가리키는 문자까지를 반환한다. 따라서 문자열의 길이는 [마지막 인덱스 - 시작 인덱스] 이다.

 

 

Examples:

    "hamburger".substring(4, 8) returns "urge"

    "smiles".substring(1, 5) returns "mile"

 

Parameters:

beginIndex - the beginning index, inclusive.

endIndex - the ending index, exclusive.

 

Returns:

the specified substring.

 

Throws:IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

출처: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#substring(int)

 

 

  • 문자열 세는 함수(for문 대체 가능)

String

.length()

문자열의 길이를 반환한다.

반응형

+ Recent posts