1. 程式人生 > >LeetCode面試常見100題( TOP 100 Liked Questions)

LeetCode面試常見100題( TOP 100 Liked Questions)

這篇文章是關於LeetCode Top 100 Liked Questions 的 專欄記錄,其中部分題目可能包括解題思路和多種優化解法。我把自己的思路都記錄在這裡,如果你看見了,請記得點個贊吧,蟹蟹【手動笑臉】。

目錄

1、Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example

:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
/**
     * Given an array of integers, return indices of the two numbers such that they add up to a specific target.
     * You may assume that each input would have exactly one solution, and you may not use the same element twice.
     * Example:
     * Given nums = [2, 7, 11, 15], target = 9,
     * Because nums[0] + nums[1] = 2 + 7 = 9,
     * return [0, 1].
     * @param
nums * @param target * @return */
public static int[] twoSum(int[] nums, int target) { int[] result= new int[2]; if(nums.length>1){ for(int i=0;i<nums.length;i++){ for(int j=i+1;j<nums.length;j++){ if(nums[i]+nums[j]==target){ result[0
]=i; result[1]=j; } } } } return result; }

2、Add Two Numbers

Description:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
/**
     * Description:You are given two non-empty linked lists representing two non-negative integers. 
     *             The digits are stored in reverse order and each of their nodes contain a single digit.
     *             Add the two numbers and return it as a linked list.
     *             You may assume the two numbers do not contain any leading zero, except the number 0 itself.
     * Example:
     * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
     * Output: 7 -> 0 -> 8
     * Explanation: 342 + 465 = 807.
     * @param l1
     * @param l2
     * @return
     */
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(0);  //建立頭結點
        ListNode phead = result;
        int flag =0;    //進位
        while(l1!=null && l2!=null ){//連個連結串列都不為空
            int val = l1.val + l2.val + flag;
            flag = 0;
            if(val>9){
                flag =1;
                val = val % 10;
            }
            //建立連結串列節點並新增到head尾
            ListNode temp = new ListNode(val);
            phead.next=temp;
            l1 = l1.next;
            l2 = l2.next;
            phead = phead.next;
        }
        if(l1 == null){//如果l1已經遍歷完成,而l2還不為空
            while(l2!=null){
                int val = l2.val + flag;
                flag =0;
                if(val >9){
                    flag =1;
                    val = val % 10;
                }
                ListNode temp = new ListNode(val);
                phead.next = temp;
                l2 = l2.next;
                phead = phead.next;
            }       
        }
        if(l2 == null){
            while(l1 !=null){
                int val = l1.val + flag;
                flag =0;
                if(val >9){
                    flag =1;
                    val = val % 10;
                }
                ListNode temp = new ListNode(val);
                phead.next = temp;
                l1 = l1.next;
                phead = phead.next;
            }
        }
        if(flag ==1){
            ListNode temp = new ListNode(1);
            phead.next = temp;
        }
        return result.next;
    }

優化解法:

/**
     * 解法二:
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode p = l1, q = l2, curr = dummyHead;
        int carry = 0;
        while (p != null || q != null) {
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            int sum = carry + x + y;
            carry = sum / 10;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            if (p != null) p = p.next;
            if (q != null) q = q.next;
        }
        if (carry > 0) {
            curr.next = new ListNode(carry);
        }
        return dummyHead.next;
    }

3、Longest Substring Without Repeating Characters

Description:
Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. 

Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

/**
     * 題目描述:
     * Given a string, find the length of the longest substring without repeating
     * characters.
     * Examples:
     *          Given "abcabcbb", the answer is "abc", which the length is 3.
     *          Given "bbbbb", the answer is "b", with the length of 1.
     *          Given "pwwkew", the answer is "wke", with the length of 3. Note that the
     * answer
     *           must be a substring, "pwke" is a subsequence and not a substring.
     * 解題思路:
     * 利用滑動視窗[i,j)表示從位置i到j的子字串str,用集合Set表示str中的字元集合,用maxL表示該字串
     * 長度,進行以下操作:
     * 1)先滑動視窗的右部邊界,即j+1,判斷str中是否出現重複字元:
     *          若果未出現,則更新Set和maxL,並繼續1)步驟
     *          如果出現重複步驟,則表示當前子串已不能再擴大長度,故執行2)步驟
     * 2)滑動視窗的左部邊界,接i+1,同時判斷str中是否包含重複字元
     * @param s
     */
    public int lengthOfLongestSubstring(String s) {

            int maxL = 0;   //記錄最大子串的長度
            Set<Character> charSet = new HashSet<Character>();
            int i=0,j=0;    //滑動視窗的起點和終點
            while(i<s.length() && j<s.length()){

                if(!charSet.contains(s.charAt(j))){
                    charSet.add(s.charAt(j));
                    maxL = Math.max(maxL,j-i+1);
                    j++;
                }else{
                    charSet.remove(s.charAt(i));
                    i++;    
                }

            }
            return maxL;     

    }
/**
     * 優化解法:
     * 思路:
     * 實際上根據以上思路我們可以得出更加優化的解法:
     * 我們可以用hashmap儲存字串的字元與索引之間的對應關係,這樣當滑動視窗檢[i,j)測出重複字元時:
     * 我們只需要找到該字元在hashmap中的索引,假定為j',那麼我們只需要將i置為j'+1,並重新開始找就可以了
     * @param args
     */
    public static int lengthOfLongestSubstring2(String s) {

        int maxL = 0;   //記錄最大子串的長度
        Map<Character,Integer> hashmap = new HashMap<Character,Integer>();
        int i=0,j=0;    //滑動視窗的起點和終點
        while(i<s.length() && j<s.length()){

            if(!hashmap.containsKey(s.charAt(j))){
                hashmap.put(s.charAt(j), j);
                maxL = Math.max(maxL,j-i+1);
                j++;
            }else{
                int index = hashmap.get(s.charAt(j));  //獲取重複字元的索引
                for(int k=i;k<=index;k++){
                    hashmap.remove(s.charAt(k));
                }
                i = index +1;   
            }
        }
        return maxL;
    }

4. Median of Two Sorted Arrays

Description:
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:

nums1 = [1, 3]
nums2 = [2]
The median is 2.0

Example 2:

nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 + 3)/2 = 2.5
/**
     * 4. Median of Two Sorted Arrays
     * Description:
     * There are two sorted arrays nums1 and nums2 of size m and n respectively.
     * Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
     * Example 1:
     * nums1 = [1, 3]
     * nums2 = [2]
     * The median is 2.0
     * Example 2:
     * nums1 = [1, 2]
     * nums2 = [3, 4]
     * The median is (2 + 3)/2 = 2.5
     *************************************************************************
     * 思路:
     * 我們將兩個有序陣列分別用A[:m-1]、B[:n-1]來表示。
     * 假定我們用A[:i-1]、A[i:m-1]將陣列A切分;用B[:j-1]、B[j:n-1]將陣列B切分;則只要保證以下條件:
     * 1)i+j = m-i + n-j;(此時,i=0~m,j=(m+n+1)/2 -i);注意為了保證j非負,這裡n>=m
     * 2)B[j-1] <= A[i],A[i-1] <= B[j]
     * 那麼我們就可以計算出:
     *      median = (max(left_part) + min(right_part))/2
     * 綜合以上思路,解題的關鍵就是尋找合適的i和j,這裡我們擬採用“二分查詢法”。步驟如下
     * 假定 imin=0,imax=m;則我們需要在[imin,imax]中尋找合適的i值,我們假設:
     * i = (imin + imax)/2,  j=(m+n+1)/2 - i,這樣我們可以保證len(left_part) = len(right_part)
     * 在以上假定之後,我們共有以下三種情況需要考慮:
     * 1) B[j-1]<= A[i] 且 A[i-1] <= B[j]: 此時 i剛好滿足情況
     * 2) B[j-1] > A[i]: 此時說明i值太小,需要增加i,這時我們需要置 imin = i+1
     * 3) A[i-1] > B[j]: 此時壽命i值過大,需要減小i,這時我們需要置 imax = i-1
     * 最終結果為:
     * 1)如果 m+n 為奇數,則 median = max(A[i-1],B[j-1])
     * 2)如果 m+n 為偶數,則 median = (max(A[i-1],B[j-1]) + min(A[i],B[j]))/2
     * 
     ************************************************************************* 
     * @param args
     */

    public static double findMedianSortedArrays(int[] A, int[] B) {
        int m = A.length;
        int n = B.length;
        //判斷第一個條件,m<=n
        if(m > n){
            int[] temp = A;
            A = B;
            B = temp;
            m = A.length;
            n = B.length;
        }
        int imin =0, imax = m;
        int i=0,j=0;
        int maxleft =0, minright=0;
        if(m==0 && n==0){
            return 0;
        }else if(m==0 && n==1){ // 當其中一個為空陣列,另一個長度為1
            return B[0];
        }else{
            while(imin <= imax){
                i = (imin+imax)/2;
                j = (m+n+1)/2 -i;
                if(i < m && B[j-1] > A[i])
                    imin = i +1;
                else if(i > 0 && A[i-1] > B[j])
                    imax = i -1;
                else{   //符合條件
                    if(i==0)
                        maxleft = B[j-1];
                    else if (j==0)
                        maxleft = A[i-1];
                    else 
                        maxleft = Math.max(A[i-1], B[j-1]);

                    if(i==m)
                        minright = B[j];
                    else if(j==n)
                        minright = A[i];
                    else 
                        minright = Math.min(B[j], A[i]);

                    break;

                }
            }
        }

        if( (m+n)%2 ==0){//為偶數
            return (maxleft + minright)/2.0;
        }else
            return maxleft;
    }

5、Longest Palindromic Substring

Description:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:

Input: "babad"
Output: "bab"

Note: “aba” is also a valid answer.
Example 2:

Input: "cbbd"
Output: "bb"
/**
     * 5、Longest Palindromic Substring 迴文結構
     * Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
     * Example 1:
     * Input: "babad"
     * Output: "bab"
     * Note: "aba" is also a valid answer.
     * Example 2:
     * Input: "cbbd"
     * Output: "bb"
     */

    /**解法一:暴力解法
     * @param s
     * @return
     */
    public static String longestPalindrome(String s) {

        int maxLength=0;
        String LongestStr="";
        int length = s.length();
        for(int i=0;i<length;i++){
            for(int j=length-1;j>=i;j--)
                if(isPalindrome(i,j,s)){
                    int subLen = j-i+1;
                    if(subLen>maxLength){
                        LongestStr = s.substring(i,j+1);
                        maxLength=subLen;
                    }
                }
        }

        return LongestStr;
    }
    /**
     * 判斷字串是否為迴文結構
     * @param startIndex
     * @param endIndex
     * @param s
     * @return
     */
    public static boolean isPalindrome(int startIndex,int endIndex,String s){
        int i=startIndex,j=endIndex;
        for(;j>=i;i++,j--){
            if(s.charAt(i)!=s.charAt(j))
                return false;
        }
        return true;
    }
/**
     * 5、 Longest Palindromic Substring
     * 優化解法二:動態規劃解法
     * 思路:
     * 利用dp[j][i]表示字串區間[j,i]是否為迴文串,則dp[i][j]
     * 即如果我們找到兩個相同的字元S[i]和S[j],在兩種情況下他們能構成迴文串:
     *      第一種:這兩個字元位置相鄰或者就是同一個字元 即:
     *          dp[j][i] = (S[i]==S[j]) && (i-j<2)
     *      第二種:這兩個字元所包含的中間字串為迴文串,這個時候我們只需要驗證:
     *          dp[j][i] = (S[i]==S[j]) && (dp[j+1][i-1] && i-j>1)
     * @param s
     * @return
     */
    public static String longestPalindrome2(String s){
        if(s.equals(""))
            return "";
        int n = s.length();
        int maxLength=0;
        String LongestStr = "";
        boolean[][] dp = new boolean[n][n];
        for(int i=0;i<n;i++){
            for(int j=0;j<=i;j++){
                /*if(s.charAt(i)==s.charAt(j) && i-j<2) //即i=j或者i=j+1
                    dp[j][i]=true;
                if(s.charAt(i)==s.charAt(j) && dp[j+1][i-1] && i-j>1)
                    dp[j][i]=true;*/
                //這行程式碼太牛皮
                dp[j][i] =(s.charAt(i)==s.charAt(j)) && (i-j<2 || dp[j+1][i-1]);

                if(dp[j][i] && maxLength<i-j+1){
                    maxLength=i-j+1;
                    LongestStr = s.substring(j,i+1);
                }
            }
        }

        return LongestStr;
    }

11. Container With Most Water

Description:
Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.

這裡寫圖片描述
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49
/**
     * 11. Container With Most Water
     *      Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai).
     *      n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). 
     *      Find two lines, which together with x-axis forms a container, such that the container contains the most water.
     * @param height
     * @return
     */
    public static int maxArea(int[] height) {
        if(height.length<1 || height ==null)
            return 0;
        int maxArea =0;
        int minval=0,j=0;
        for(int i=0;i<height.length;i++){
            j=height.length;
            /*minval =Math.min(height[i],height[j]);
            if(minval*(j-i)>maxArea)
                maxArea = minval*(j-i);*/
            if(i>0 && height[i]<height[i-1])
                continue;
            while(i<j){
                //包含的數值變大時才計算
                if(j==height.length || (height[j]<height[j-1] && height[j]<height[i])){
                    minval = Math.min(height[i],height[j-1]);
                    if(minval*(j-1-i)>maxArea)
                        maxArea=minval*(j-1-i);
                }
                j--;    
            }
        }
        return maxArea;
    }
/**
     * 11. Container With Most Water
     * 優化解法二:
     * 我們用兩個指標分別指向陣列height的兩端,我們首先比較height[i]和height[j]的大小
     * 如果      height[i]>height[j] 則我們保留height[i],height[j--]
     *      否則,我們保留height[j],將height[i++]
     * 這樣做是因為,面積的大小是由更小的那個值來決定,保留更小的值,同時將更大值的指標向靠近方向移動,無論如何是得不到更大的值的
     * @param height
     * @return
     */
    public static int maxArea2(int[] height) {
        int start=0,end=height.length-1;
        int maxVal=0;   //儲存面積的最大值
        while(start<end){
            maxVal = Math.max(Math.min(height[start],height[end])*(end-start),maxVal);
            //接著移動指標
            if(height[start]<height[end])
                start++;
            else
                end--;
        }
        return maxVal;
    }

15. 3Sum

Description:
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:

Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]
/**
     * 15. 3Sum
     * Given an array nums of n integers, are there elements a, b, c 
     * in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
     * Note:The solution set must not contain duplicate triplets.
     * Example:
     * Given array nums = [-1, 0, 1, 2, -1, -4],
     * A solution set is
     * [[-1, 0, 1],
     * [-1, -1, 2]]
     * @param nums
     * @return
     */
    /**
     * 傳統的暴力解法需要O(N_3)的時間複雜度,因此我們可以這樣優化演算法:
     * 1、先用快排,將整個陣列排序
     * 2、然後對於每一個排序後的元素,用兩個值的和等於某個定值的方法去解
     * @param nums
     * @return
     */
    public static List<List<Integer>> threeSum(int[] nums) {

        List<List<Integer>> result = new LinkedList<List<Integer>>();   //最終輸出結果
        if(nums == null || nums.length<3)
            return result;
        Arrays.sort(nums);   //java排序
        //排序後繼續檢查邊界
        if(nums[0]>0 || nums[nums.length-1]<0)
            return result;
        for(int i=0;i<nums.length-2;i++){
            if(i==0 || nums[i]!=nums[i-1]){
                int low = i+1,high = nums.length-1,sum = 0-nums[i];
                while(low<high){
                    if(nums[low]+nums[high]==sum){
                        result.add(Arrays.asList(nums[i],nums[low],nums[high]));
                        while(low<high && nums[low]==nums[low+1])
                            low++;
                        while(low<high && nums[high]==nums[high-1])
                            high--;
                        low++;high--;
                    }else if(nums[low]+nums[high]<sum)
                        low++;
                    else {
                        high--;
                    }
                }
            }
        }
        return result;
    }

16. 3Sum Closest

Description:
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:

Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
/**
     * 16. 3Sum Closest
     * Given an array nums of n integers and an integer target, find three integers in nums 
     * such that the sum is closest to target. Return the sum of the three integers. 
     * You may assume that each input would have exactly one solution.
     * Example:
     * Given array nums = [-1, 2, 1, -4], and target = 1.
     * The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
     * @param nums
     * @param target
     * @return
     */
    public static int threeSumClosest(int[] nums, int target) {

        Arrays.sort(nums);
        int result = nums[0]+nums[1]+nums[nums.length-1];   //儲存最終結果
        for(int i=0;i<nums.length-2;i++){
            int low= i+1,high=nums.length-1;
            int temp = 0;
            while(low<high){
                temp=nums[i]+nums[low]+nums[high];
                if(temp>target)
                    high--;
                else if(temp<target)
                    low++;
                else{//相等  
                    return target;
                }
                if(Math.abs(temp-target)<Math.abs(result-target)){
                    result = temp;
                }
            }
        }
        return result;    
    }

17. Letter Combinations of a Phone Number

Description:
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

這裡寫圖片描述
Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

/**
     * 17. Letter Combinations of a Phone Number
     * Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
     * 方法一:遞迴方法
     * @param digits
     * @return
     */
    static String[] keyMapping ={"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    public static List<String> letterCombinations(String digits) {

        List<String> result= new LinkedList<>();
        if(digits.equals(""))
            return result;
        combinationLetter("",digits,0,result);
        return result;     
    }
    /**
     * 遞迴拼接字串
     * @param prefix 單個拼接的字串
     * @param digits  輸入數字集
     * @param index 
     * @param result 結果列表
     */
    public static void combinationLetter(String prefix,String digits,int index,List<String> result){

        //遞迴結束條件
        if(index>=digits.length()){
            result.add(prefix);
            return;
        }
        //取出按鍵對應的字串
        String letters = keyMapping[digits.charAt(index)-'0'];
        for(int i=0;i<letters.length();i++){
            combinationLetter(prefix+letters.charAt(i), digits, index+1, result);
        }
    }
/**
     * 方法二:使用佇列
     * @param digits
     * @return
     */
    public static List<String> letterCombinations2(String digits){

        List<String> result= new LinkedList<>();
        if(digits.equals(""))
            return result;
        Queue<String> strQueue = new LinkedList<>();
        String mapStr;
        strQueue.offer("");
        strQueue.offer("flag");
        for(int i=0;i<digits.length();i++){
            mapStr = keyMapping[digits.charAt(i)-'0'];      //取數字對映的字串
            while(strQueue.peek()!="flag"){     //每組字串新增完後都加一個標記
                for(int j=0;j<mapStr.length();j++){
                    String ch = mapStr.substring(j,j+1);
                    strQueue.offer(strQueue.peek()+ch);
                }
                strQueue.poll();
            }
            strQueue.offer("flag"); //在佇列末尾加標記位
            strQueue.poll();    //刪除佇列頭節點
        }
        //遍歷佇列
        while(!strQueue.isEmpty())
            result.add(strQueue.poll());
        result.remove(result.size()-1);
        return result;
    }
public static List<String> letterCombinations3(String digits){

        LinkedList<String> result= new LinkedList<>();
        if(digits.equals(""))
            return result;
        result.add("");
        while(result.peek().length() != digits.length()){   //注意終止條件通過佇列頭的字串長度來判斷
            String first = result.poll();
            String mapStr = keyMapping[digits.charAt(first.length())-'0'];  //根據取出的佇列頭元素的長度來查詢對映字典
            for(int i=0;i<mapStr.length();i++)
                result.offer(first+mapStr.charAt(i));
        }
        return result;
    }

19. Remove Nth Node From End of List

Description:
Given a linked list, remove the n-th node from the end of list and return its head.
Example:

Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:

Given n will always be valid.

Follow up:
Could you do this in one pass?

/**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    /**
     * 19. Remove Nth Node From End of List
     * Given a linked list, remove the n-th node from the end of list and return its head.
     * 思路:
     * 給定兩個指標first,second 我們只需要first先遍歷N個節點,讓後兩個一起開始遍歷,那麼當first到達尾部之後,second即為倒數第N個節點
     * @param head
     * @param n
     * @return
     */
    public static ListNode removeNthFromEnd(ListNode head, int n) {

        ListNode first=head,preCur=head;
        int index=n+1;//需要記錄待刪除節點的父節點,所以加1
        //first指標先遍歷n+1個節點
        while(index-->0){
            first = first.next;
            if(first==null && index>0)  //index>0說明不存在待刪除節點的父節點,即刪除的就是頭節點
                return head.next;
        }
        //兩個指標一起遍歷
        while(first!=null){
            first=first.next;
            preCur=preCur.next;
        }
        preCur.next=preCur.next.next;
        return head;
    }

20. Valid Parentheses

Description:
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true
 /**
     * 20. Valid Parentheses
     * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
     * An input string is valid if:
     * Open brackets must be closed by the same type of brackets.
     * Open brackets must be closed in the correct order.
     * Note that an empty string is also considered valid.
     * Example 1:
     * Input: "()"
     * Output: true
     * @param s
     * @return
     */
    public static boolean isValid(String s) {

        if(s==null || s.isEmpty())
            return true;
        //初始化一個棧
        Stack<Character> stack = new Stack<>();
        for(int i=0;i<s.length();i++){
            Character ch = s.charAt(i);
            if(!stack.isEmpty()){
                if((stack.peek()=='('&& ch==')') || (stack.peek()=='['&& ch==']') || (stack.peek()=='{'&& ch=='}')){
                    stack.pop();
                    continue;
                }
            }   
            stack.push(ch);
        }
        return stack.isEmpty();
    }

21. Merge Two Sorted Lists

Description:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
/**
     * 21. Merge Two Sorted Lists
     * Merge two sorted linked lists and return it as a new list. 
     * The new list should be made by splicing together the nodes of the first two lists.
     * Example:
     * Input: 1->2->4, 1->3->4
     * Output: 1->1->2->3->4->4
     * @param l1
     * @param l2
     * @return
     */
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2){
        ListNode p1=l1,p2=l2;
        ListNode phead = new ListNode(-1);  //建立頭結點
        ListNode index=phead;
        while(p1!=null && p2!=null){
            if(p1.val<=p2.val){
                index.next=p1;
                p1=p1.next;
                index=index.next;
            }else{
                index.next=p2;
                p2=p2.next;
                index=index.next;
            }
        }
        if(p1!=null)
            index.next=p1;
        if(p2!=null)
            index.next=p2;
        return phead.next;
    }
    public List<String> generateParenthesis(int n) {
        return generate("",n,0,0);

    }

22. Generate Parentheses

Description:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]
/**
     * 22. Generate Parentheses
     * Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
     * @param parenthese
     * @param num
     * @param left 左括號數
     * @param right 右括號數
     * @return
     */
    public static List<String> generate(String parenthese,int num,int left,int right){

        List<String> result = new ArrayList<String>();
        if(left < num){
            //生成的左括號數大於右括號數,則下一個括號可以為左括號,也可以為右括號
            if(left>right){
                result.addAll(generate(parenthese+"(",num,left+1,right));
                result.addAll(generate(parenthese+")",num,left,right+1));
            }
            else{   //左括號數和右括號數相同時,一定是新增左括號
                result.addAll(generate(parenthese+"(",num,left+1,right));
            }
        }
        
            
           

相關推薦

LeetCode面試常見100 TOP 100 Liked Questions

這篇文章是關於LeetCode Top 100 Liked Questions 的 專欄記錄,其中部分題目可能包括解題思路和多種優化解法。我把自己的思路都記錄在這裡,如果你看見了,請記得點個贊吧,蟹蟹【手動笑臉】。 目錄: 1、Two Su

Android面試一天一15 Day:ContentProvider

有一次HR給我了一份簡歷,說是一個資深的工程師,比較特別的是翻譯過一本《Andorid XXXX》的書,基本涵蓋了Android開發的要點,而且還是有深度的。正好我看過此書的一些章節,面試了一下之後,這個面試者比較顯著的特點就是對自己翻譯過的章節的知識點也不太

Android面試一天一14 Day:SharedPreferences

如果說程式可以簡單理解成“指令和資料的集合”,那麼你在任何平臺上程式設計都難以離開資料儲存,在Android平臺上自然也不會例外。說到資料的儲存,對於Key-Value對應的資料存取,Android提供SharedPreferences的方式可以進行方便的操作。

深度學習面試100第31-35

31.梯度爆炸會引發什麼問題?解析:在深度多層感知機網路中,梯度爆炸會引起網路不穩定,最好的結果

深度學習面試100第36-40

36、簡單說下sigmoid啟用函式解析:常用的非線性啟用函式有sigmoid、tanh、rel

深度學習面試100第51-55

點選藍字關注我們,小七等你好久嘍51、初始化如何影響訓練? 解析:方法:我們生成兩個 12 維高

深度學習面試100第16-20

1、為什麼引入非線性激勵函式?解析:第一,對於神經網路來說,網路的每一層相當於f(wx+b)=f

python面試1006

模擬 切片 Python面試 pan turn 地址 while span http 7.請反轉字符串 "aStr"? print("aStr"[::-1]) python實現字符串反轉 第一種:使用字符串切片 result = s[::-1] 第

python面試10020

程序模塊化 現在 timeit 停止 elf tools 重用 一份 不可變 76.遞歸函數停止的條件? 遞歸的終止條件一般定義在遞歸函數內部,在遞歸調用前要做一個條件判斷,根據判斷的結果選擇是繼續調用自身,還是return;返回終止遞歸。終止的條件:1、判斷遞歸的次數是

python面試10019

file 通信 dsw urn ria isp 其它 details 有時 61.如何在function裏面設置一個全局變量 Python中有局部變量和全局變量,當局部變量名字和全局變量名字重復時,局部變量會覆蓋掉全局變量。 如果要給全局變量在一個函數裏賦值,必須使用g

c++刷3/100數獨,棧和隊列

彈出 iter char col 編寫 實現 滑動窗口 title 表示 stack的基本操作 ? s.size():返回棧中的元素數量 ? s.empty():判斷棧是否為空,返回true或false ? s.push(元素):返回對棧頂部“元素”的可變(可修改)引用 ?

c++刷15/100矩陣轉置,最深子樹

標記 i++ con 結果 最短 網上 矩陣的轉置 alloc tree 題目一:矩陣轉置 給定一個矩陣 A, 返回 A 的轉置矩陣。 矩陣的轉置是指將矩陣的主對角線翻轉,交換矩陣的行索引與列索引。 示例 1: 輸入:[[1,2,3],[4,5,6],[7,8,9]]

c++刷21/100樹的打印、矩陣覆蓋和括號生成

生成 一個 ring 第一個 pop 全局 over 矩形 node 題目一:把二叉樹打印成多行 從上到下按層打印二叉樹,同一層結點從左至右輸出。每一層輸出一行。 思路:一開始以為2維的vector可以直接訪問,但是試了是不行,會報錯,vector在有值之前不能直接訪問,所

c++leetcode大寫轉小寫 速度超越100%。

思路分析 1.大寫轉小寫就是其ascii碼值加32,同理小寫轉大寫,就是-32; string toLowerCase(string str) { for(int i=0;i<str.size();i++){ i

微軟公司等資料結構 演算法面試100 第1 100 全部出爐

微軟等100題系列V0.1版終於結束了。從2010年10月11日當天最初發表前40題以來,直至此刻,整理這100題,已有近2個月。2個月,因為要整理這100題,很多很多其它的事都被我強迫性的擱置一旁,如今,要好好專心去做因這100題而被耽誤的、其它的事了。這微軟等資料結構+演算法面試100題系列(是的,系列)

微軟10064尋找第1500個醜數

題目:我們把只包含因子2、3和5的數稱作醜數(Ugly Number)。例如6、8都是醜數,但14不是,因為它包含因子7。習慣上我們把1當做是第一個醜數。 求按從小到大的順序的第1500個醜數。 思路: 最直觀的方法,逐一判斷是不是醜數,知道找到1500個醜數 bool

微軟10093找出陣列中比左邊的大比右邊的小的元素

在一個int數組裡查詢這樣的數,它大於等於左側所有數,小於等於右側所有數 思路:如果一個元素師左邊最大的,又是右邊最小的,那麼就是要找的元素,所以一開始求出所有的右邊最小陣列rightmin,然後從左往右判斷截止當前元素最大的是,如果和對應的rightemin陣列中一樣

c語言實用經典1001-10

【程式1】題目:有1、2、3、4個數字,能組成多少個互不相同且無重複數字的三位數?都是多少?1.程式分析:可填在百位、十位、個位的數字都是1、2、3、4。組成所有的排列後再去      掉不滿足條件的排列。2.程式原始碼:#include<stdio.h> #in

【LDU】新生訓練營杭電100

A - ASCII碼排序  輸入三個字元後,按各字元的ASCII碼從小到大的順序輸出這三個字元。 Input輸入資料有多組,每組佔一行,有三個字元組成,之間無空格。 Output對於每組輸入資料,輸出一行,字元中間用一個空格分開。 Sample Input qwe