[leetcode] Easy-58번. Search Insert Position 문제풀이

반응형
728x90
반응형

문제

https://leetcode.com/problems/search-insert-position/

 

Search Insert Position - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

 

 

풀이 코드

package SITE03_leetcode.easy;

import java.util.Objects;

/**
 * https://leetcode.com/problems/search-insert-position/
 */
public class E004_leetCode58_LengthofLastWord {
    public static void main(String[] args) {
        E004_leetCode58_LengthofLastWord solution = new E004_leetCode58_LengthofLastWord();

        System.out.println(solution.lengthOfLastWord("   fly me   to   the moon  "));
    }

    public int lengthOfLastWord(String s) {
        int result = 0;
        boolean isInit = false;

        for (int i = s.length() - 1; i >= 0; i--) {
            if (!Objects.equals(String.valueOf(s.charAt(i)), " ")) {
                isInit = true;
                result++;
            } else {
                if (isInit) {
                    break;
                }
            }
        }

        return result;
    }
}

 

첫번째로 공백을 만났을 경우를 flag 변수를 통해 처리했다. 더 좋은 방법이 있을거같아, 확인해보았다.

 

더 좋은 방법

package SITE03_leetcode.easy;

import java.util.Objects;

/**
 * https://leetcode.com/problems/search-insert-position/
 */
public class E004_leetCode58_LengthofLastWord {
    public static void main(String[] args) {
        E004_leetCode58_LengthofLastWord solution = new E004_leetCode58_LengthofLastWord();

        System.out.println(solution.lengthOfLastWord2("   fly me   to   the moon  "));
    }

    public int lengthOfLastWord(String s) {
        if (null == s || s.trim().length() == 0) return 0;

        //"   fly me   to   the moon  "
        s = s.trim();
        // "fly me   to   the moon" - 양 옆의 공백 제거

        // 마지막 공백 기준으로 자르기
        String lastWord = s.substring(s.lastIndexOf(" ") + 1);

        return lastWord.length();
    }
}

 

주석을 보고 코드를 이해하자. 문자열의 substring 메서드를 사용하여 간단하게 풀이할 수 있다. 참고로 앞뒤 공백 제거는 trim() 메서드 이외에도 JAVA11에 등장한 strip() 메서드도 사용할 수 있다.

 

 

반응형

Designed by JB FACTORY