본문 바로가기
Algorithm/LeetCode

Leetcode - 557. Reverse Words in a String III

by HaningYa 2020. 4. 29.
728x90

 

[Must do Easy Question]

 

How to effectively use LeetCode to prepare for interviews!! - LeetCode Discuss

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

 

Reverse Words in a String III - 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


문제

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"

Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.


하나의 공백으로 분리된 단어들을 거꾸로 나열하면 된다.

 

주어진 String을 공백으로 나누어 String 배열에 집어넣고 각각의 String 마다 reverse 함수를 통해 앞뒤를 바꾸어 마지막에 합친다.

 

맨 마지막에 공백이 추가되는 문제 때문에 답을 return 할 String 의 마지막 item을 없애고 리턴한다.

 

import java.util.*;
class Solution {
    public String reverseWords(String s) {
        String answer = "";
        
        if (s.length() == 0){
            return "";
        }
        
        String[] strArray = s.split(" ");
        for(String str : strArray){
            answer = answer + reverse(str);
        }
        return answer.substring(0, s.length());
    }
    
    public String reverse(String str){
        char[] charArray = str.toCharArray();
        int size = charArray.length;
        for(int i = 0 ; i < size/2; i++){
            char tmp = charArray[i];
            charArray[i] = charArray[size-i-1];
            charArray[size-i-1] = tmp;
           
        }
        return String.valueOf(charArray) + " ";
    }
}

 

Success

Details 

Runtime: 12 ms, faster than 30.15% of Java online submissions for Reverse Words in a String III.

Memory Usage: 40.5 MB, less than 21.05% of Java online submissions for Reverse Words in a String III.

 


 

728x90

'Algorithm > LeetCode' 카테고리의 다른 글

LeetCode - 146. LRU Cache  (4) 2020.05.26
Leetcode - 2. Add Two Sum  (0) 2020.05.25
Leetcode - 448. Find All Numbers Disappeared in an Array  (0) 2020.04.23
Leetcode - 226 . Invert Binary Tree  (0) 2020.04.20
Leetcode - 205. Isomorphic Strings  (1) 2020.04.17

댓글