본문 바로가기

DEV/알고리즘&자료구조

[Leetcode] 오늘의 문제 - 214. Shortest Palindrome

728x90
반응형

문제

214. Shortest Palindrome

You are given a string s. You can convert s to a palindrome by adding characters in front of it.

Return the shortest palindrome you can find by performing this transformation.

 

 

키워드

String
Rolling Hash
String Matching
Hash Function

 

 

내 첫번째 접근

  • Deque 자료구조를 Stack처럼 사용해보려고 했다.

 

문자열 뒤집기

  • StringBuilder의 reverse() 메서드로 문자열을 뒤집을 수 있다.

 

코드

import java.lang.StringBuilder;

class Solution {
    public String shortestPalindrome(String s) {
        String reverseStr = new StringBuilder(s).reverse().toString();

        for (int i = 0; i < reverseStr.length(); ++i)
            if (s.startsWith(reverseStr.substring(i)))
                return reverseStr.substring(0, i) + s;

        return reverseStr + s;	
    }
}

 

 

Git

https://github.com/dev-jinius/Algorithm-Practice/tree/main/LeetCode/0214-shortest-palindrome

 

Algorithm-Practice/LeetCode/0214-shortest-palindrome at main · dev-jinius/Algorithm-Practice

Contribute to dev-jinius/Algorithm-Practice development by creating an account on GitHub.

github.com

 

728x90
반응형