티스토리 뷰

문제주소

leetcode.com/problems/palindrome-number/

leetcode.com/problems/longest-common-prefix/

leetcode.com/problems/linked-list-cycle/

내 풀이 && 다른 사람 풀이

    public static boolean isPalindrome(int x) {
        String original = String.valueOf(x);
        StringBuilder reversed = new StringBuilder();
        for (int i = original.length() - 1; i > -1; i--) {
            reversed.append(original.charAt(i));
        }
        return original.equals(reversed.toString());
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        Arrays.sort(strs, Comparator.comparingInt(String::length));
        String prefix = "";
        while (strs[0].length() > -1) {
            prefix = strs[0];
            int count = strs.length;
            for (String word : strs) {
                if (word.startsWith(prefix)) {
                    count--;
                }
            }
            if (count == 0) {
                break;
            } else {
                strs[0] = strs[0].substring(0, strs[0].length() - 1);
            }
        }
        return prefix;
    }
    
    /*
    생각보다 너무 계속 틀리고 오래걸렸다.ㅠㅠ
    다른 풀이 : 리츠코드 솔루션
	public String longestCommonPrefix(String[] strs) {
    	if (strs.length == 0) return "";
    	String prefix = strs[0];
    	for (int i = 1; i < strs.length; i++)
        	while (strs[i].indexOf(prefix) != 0) {
            	prefix = prefix.substring(0, prefix.length() - 1);
            	if (prefix.isEmpty()) return "";
        	}
    	return prefix;
	}
     */

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    // https://leetcode.com/problems/linked-list-cycle/ 에서 실행됨
    public boolean hasCycle(ListNode head) {
        Set<ListNode> nodes = new HashSet<>();
        if(head == null || head.next == null){
            return false;
        }
        while( head.next != null){
            if( nodes.contains(head)){
                return true;
            }
            nodes.add(head);
            head = head.next;
        }
        return false;
    }
}

LongestCommonPrefix 문제가 꽤 오래걸렸다. 맞는걸 찾아가는 것보다 큰 것을 설정하고 줄여나가는 것이 더 간편했다. 잘 안 된다면 반대로 생각해보자! 그리고 0일 경우, 항상 한 번 더 생각해보자. 특이한 케이스에 해당되는 경우가 많다. null이거나 0이거나 1인 경우 등등!

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함