LeetCode - 151. Reverse Words in a String(String, Two Pointers)

YAMAMAMO·2022년 2월 16일
0

LeetCode

목록 보기
27/100

문제

입력 문자열이 주어지면 단어의 순서를 반대로 한다.s단어는 공백이 아닌 문자의 시퀀스로 정의됩니다. 의 단어는 적어도 한 칸 이상 구분됩니다.s단어 문자열을 공백으로 연결된 역순으로 반환합니다.
두 단어 사이에 선행 또는 후행 공백 또는 여러 공백을 포함할 수 있습니다. 반환되는 문자열에는 단어를 구분하는 공백이 하나만 있어야 합니다. 여백은 포함하지 마십시오.

Given an input string , reverse the order of the words.s
A word is defined as a sequence of non-space characters. The words in will be separated by at least one space.s
Return a string of the words in reverse order concatenated by a single space.
Note that may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.s

https://leetcode.com/problems/reverse-words-in-a-string/

Example 1:

Input: s = "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: s = " hello world "
Output: "world hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: s = "a good example"
Output: "example good a"
Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

풀이

자바입니다.

  • split을 사용해서 각 단어들을 배열에 담는다.
  • words[i].equals("") 사용해서 공백을 필터링한다.
  • trim() 은 문자열의 앞,뒤 공백을 없앤다.
class Solution {
    public String reverseWords(String s) {
        String[] words = s.split(" ");// 정규표현식 \\s
        StringBuilder res = new StringBuilder();
        for(int i=words.length-1;i>=0;i--){
            if(!words[i].equals("")) {
                res.append(words[i]+" ");
            }
        }
        
        return res.toString().trim();

    }
}

LeetCode를 풀면서 가장 큰 고민은 추가메모리(공간)를 사용해서 풀지 여부였다. 그래서 한 동안은 추가공간을 사용하는 방식을 사용하지 않았다. 그러다보면 시간복잡도가 커져서 TimeLimt... 에 걸리는 경우가 많았다. 공간, 시간 복잡도 사이에서 균형을 잡기 어렵다.

profile
안드로이드 개발자

0개의 댓글