1. 程式人生 > 實用技巧 >leetcode題解

leetcode題解

**1. 力扣21題 —— 合併兩個有序連結串列 **

public class MergerTwoLinkList {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}

public class ListNode {
    int val;
    ListNode next;

    public ListNode(int val) {
        this.val = val;
    }
}

}

2. 力扣820 —— 單詞的壓縮編碼

public class CompressCoding {
public int minimumLengthEncoding1(String[] words) {

    Set<String> set = new HashSet<>(Arrays.asList(words));
    for (String str : words) {
        for (int i = 1; i < str.length(); i++) {
            set.remove(str.substring(i));
        }
    }

    //利用set的流獲取最後的總和
    return set.stream().mapToInt(x -> x.length() + 1).sum();
}

}

3. 力扣20 —— 有效的括號

public class EffectiveStr {
Map<Character, Character> map;

public EffectiveStr() {
    map = new HashMap<Character, Character>(3);
    map.put('}', '{');
    map.put(']', '[');
    map.put(')', '(');
}

public boolean isValid(String s) {
    Stack<Character> stack = new Stack<>();
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (map.containsKey(c)) {
            if (stack.isEmpty()) {
                return false;
            }
            if (map.get(c) != stack.pop()) {
                return false;
            }
        } else {
            stack.push(c);
        }
    }
    if (stack.isEmpty()) {
        return true;
    }
    return false;
}

}

4. 力扣3 無重複字元的最長子串

public class LongestSubStr {
public int lengthOfLongestSubstring(String s) {
if (s == ""){
return 0;
}
int max = 0;
List list = new ArrayList<>(s.length());
for (int i = 0; i < s.length(); i++) {
for (int j = i; j < s.length(); j++) {
if (list.contains(s.charAt(j))) {
list.clear();
break;
} else {
list.add(s.charAt(j));
}
if (max < list.size()) {
max = list.size();
}
}
if (max < list.size()) {
max = list.size();
}
}
return max;
}

5. 力扣2 —— 兩數相加

public class AddTwoNumByLinkList {
static class ListNode {
int val;
ListNode next;

    public ListNode(int val) {
        this.val = val;
    }
}

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    // 先建立一個連結串列,第一個數值為0
    ListNode temp = new ListNode(0);
    ListNode next = temp;
    ListNode head1 = l1;
    ListNode head2 = l2;
    // 因為數值是按照個位數開始相加的,故最大是9+9 = 19 ,進位為1   carry 的值為 0或者 1
    int carry = 0;
    while (head1 != null || head2 != null) {
        int head11 = head1 == null ? 0 : head1.val;
        int head22 = head2 == null ? 0 : head2.val;
        next.next = new ListNode((head11 + head22 + carry) % 10);
        carry = (head11 + head22 + carry) / 10;
        head1 = head1.next;
        head2 = head2.next;
        next = next.next;
    }
    // 防止最後的進位  例如 9+9 = 18 ,有額外的進位18
    if (carry > 0) {
        next.next = new ListNode(carry);
    }
    return temp.next;
}

public static void display(ListNode listNode) {
    ListNode head = listNode;
    while (head != null) {
        System.out.println(head.val);
        head = head.next;
    }
}

6. 力扣7 —— 整數反轉

public int reverse(int x) {
int result;
Stack stack = new Stack<>();
String str = String.valueOf(x);
for (int i = 0; i < str.length(); i++) {
stack.push(str.charAt(i));
}
StringBuilder builder = new StringBuilder();
while (!stack.empty()) {
builder.append(stack.pop());
}
String strReverse = builder.toString();
// 沒有找到-號 說明是正數,直接判斷有沒有大於最大值 若沒有直接返回
if (strReverse.indexOf('-') == -1) {
result = strToInt(strReverse);
} else {
strReverse = strReverse.substring(0, strReverse.length() - 1);
strReverse = "-" + strReverse;
result = strToInt(strReverse);
}

    return result;
}

public int strToInt(String str) {
    try {
        return Integer.parseInt(str);
    } catch (Exception e) {
        return 0;
    }
}