Algorithm🧠/LeetCode

[LeetCode] Palindrome (회문)

개발자겨려 2025. 5. 2. 23:15

 

 

문자열일 경우🧠

    private static boolean isPalindromeTowPointer (String str) {
    	// 양쪽으로 비교
        str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]]","");

        int left = 0;
        int right = str.length()-1;

        while(left<right) {
            if(str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    private static boolean isPalindromeRecursion (String str, int start, int end) {
    	// 재귀함수를 이용한 방법
        if(start >= end) {
            return true;
        }
        if(str.charAt(start) != str.charAt(end)) {
            return  false;
        }
        return isPalindromeRecursion(str, start+1, end-1);
    }

    private static boolean isPalindromeLamda (String str) {
    	//Java 8 스트림(Streams)
        String str2 = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", "");
        return IntStream.range(0, str.length() / 2)
                .allMatch(i -> str2.charAt(i) == str2.charAt(str2.length() - i - 1));
    }

    private static boolean isPalindromeSB(String str) {
        String clean = str.toLowerCase();
        String reverse = new StringBuilder(clean).reverse().toString();
        return clean.equals(reverse);
    }

 

 

숫자일 경우🧠

    public static boolean isPalindrome(int num) {
    // 반복문을 통해 10으로 나눈 나머지 값을 reversNumber 만들어서 비교
        if(num < 0) {return false;}

        int originNumber = num;
        int rev = 0;

        while( num > 0) {
            int remainder = num % 10 ;
            rev = rev * 10 + remainder;
            num /= 10;
        }

        return originNumber == rev;
    }

    private static boolean isPalindromeRecursive(int num, int rev) {
        // 위와 같은 원리, 재귀(Recursion)를 이용한 방법
        if (num < 10) {
            return rev * 10 + num == num;
        } else {
            int lastDigit = num % 10;
            rev = rev * 10 + lastDigit;
            return isPalindromeRecursive(num / 10, rev);
        }
    }

    private static boolean isPalindromeBingInteger (BigInteger num) {
        BigInteger reverseNumber = new BigInteger(new StringBuilder(num.toString()).reverse().toString());
        return num.compareTo(reverseNumber) == 0;
    }

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

[LeetCode] TwoSum  (0) 2025.04.21