코린이의 소소한 공부노트

[LeetCode/Easy] 2490. Circular Sentence 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 2490. Circular Sentence

무지맘 2023. 5. 5. 23:18

1. Input

1) String sentence

 

2. Output

1) sentence의 단어들이 순서대로 끝말잇기로 연결된다면 true, 아니면 false

- 단어는 공백문자 1개로 구분되어 있다.

- 가장 마지막 단어와 첫 단어도 연결되어야 한다.

 

3. Constraint

1) 1 <= sentence.length <= 500

2) sentence는 영어 대소문자와 공백문자로 이루어져 있다.

3) 불필요한 공백은 없다.

 

4. Example

Input: sentence = "leetcode exercises sound delightful" -> Output: true

Input: sentence = "Leetcode is cool" -> Output: false

 

5. Code

1) 첫 코드(2023/05/05)

class Solution {
    public boolean isCircularSentence(String sentence) {
        String[] word = sentence.split(" ");
        boolean answer = true;
        int n = word.length;
        for(int i=0 ; i<n-1 && answer; i++)
            if(word[i].charAt(word[i].length()-1)!=word[i+1].charAt(0))
                answer = false;
        return answer && word[n-1].charAt(word[n-1].length()-1)==word[0].charAt(0);
    }
}

2) 힌트를 보고 split() 없이 해본 코드(2023/05/05)

class Solution {
    public boolean isCircularSentence(String sentence) {
        boolean answer = true;
        for(int i=1 ; i<sentence.length()-1 && answer ; i++)
            if(sentence.charAt(i)==' ')
                if(sentence.charAt(i-1)!=sentence.charAt(i+1))
                    answer = false;
        return answer? sentence.charAt(0)==sentence.charAt(sentence.length()-1) : false;
    }
}

- 실행 시간은 같았고, 메모리 사용량이 확 줄었다.