1. 程式人生 > >【LeetCode】Day 1

【LeetCode】Day 1

文章目錄

771. Jewels and Stones

給一字串 J (大小寫敏感)和一個字串 S, 求S中包含多少J中的字元。
例如:
輸入: J = “aA”, S = “aAabbc”,
輸出: 3
解釋: S中出現’a’, 'A’一共3次

    public int numJewelsInStones(String J, String S) {
        int r = 0;
        for (char c : S.toCharArray()) {//遍歷S
            if (J.indexOf(c) != -1) {//判斷J中是否包含,有則計數+1
                r++;
            }
        }
        return r;
    }

上述複雜度為O(M*N)
判斷J中是否包含那裡,可以先把J中的字元放到Set中,這樣每次判斷是否存在就為O(1)
優化後如下

    public int numJewelsInStones(String J, String S) {
        int r = 0;
        Set<Character> set = new HashSet<>();
        for (char c : J.toCharArray()) {//存入Set
            set.add(c);
        }
        for (char c : S.toCharArray()) {//遍歷S
            if (set.contains(c)) {//判斷J中是否包含,有則計數+1
r++; } } return r; }

929. Unique Email Addresses

每個電子郵箱以@分隔,分為字首和字尾。除了小寫字母,還能包含"." , “+”, 字首中,無視任何"." , 無視"+"號後面的字母
例如:
輸入: [[email protected], [email protected], [email protected]]
輸出: 2
解釋: [[email protected], [email protected]]兩個

    public int numUniqueEmails(String[] emails) {
        Set<String> set = new HashSet<>();
        for (String email : emails) {
            String[] ss = email.split("@");//以@分隔
            //只處理@前面的部分
            ss[0] = ss[0].replaceAll(".", "").split("+")[0];//先把所有"."去除,然後以"+"分隔,只取"+"前面部分
            set.add(ss[0] + ss[1]);//放進Set中,去重
        }
        return set.size();
    }

709. To Lower Case

字串轉小寫

    public String toLowerCase(String str) {
        StringBuilder sb = new StringBuilder();
        for (char c : str.toCharArray()) {
            //或運算0x20(32)(0b0010_0000),相當於把二進位制第6位變為1,Ascii碼中這一位大寫字元都為0,小寫都為1,恰好對應。"或"0x20變1轉小寫,"與"0xDF(0b1101_1111)變0轉大寫,"異或"0x20大小寫互轉。
            sb.append((char) (c | 0x20));
        }
        return sb.toString();
    }

944. Delete Columns to Make Sorted

給一個字串陣列,每個字串長度都相同。給一個刪除索引序列 {i},刪除每個字串中第 i 個字元。。
例如: A = [
“abcdef”,
“uvwxyz”
]
刪除索引為 {0, 2, 3}的字元後後
A = [
“bef”,
“vyz”
]
從上往下為閱讀[“b”, “v”], [“e”, “y”], [“f”, “z”] ,為非降序字串(b < v, e < y, f < z),
求最少刪除多少個,能使剩下的字串為非降序(即a <= b)

    public int minDeletionSize(String[] A) {
        int c = 0;
        int len = A.length;
        for (int col = 0; col < A[0].length(); col++) {//列
            for (int row = 0; row < len - 1; row++) {//行
                //如果 A[row][col] > a[row+1][col],說明這一列有降序的字元,根據題意要把這列刪了,但題目只需要記錄數量,所以只需計數器+1
                if (A[row].charAt(col) > A[row + 1].charAt(col)) {
                    c++;
                    break;
                }
            }
        }
        return c;
    }

804. Unique Morse Code Words

International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: “a” maps to “.-”, “b” maps to “-…”, “c” maps to “-.-.”, and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:

[".-","-…","-.-.","-…",".","…-.","–.","…","…",".—","-.-",".-…","–","-.","—",".–.","–.-",".-.","…","-","…-","…-",".–","-…-","-.–","–…"]

Now, given a list of words, each word can be written as a concatenation of the Morse code of each letter. For example, “cba” can be written as “-.-…–…”, (which is the concatenation “-.-.” + “-…” + “.-”). We’ll call such a concatenation, the transformation of a word.
Return the number of different transformations among all words we have.

Example:
Input: words = [“gin”, “zen”, “gig”, “msg”]
Output: 2
Explanation:
The transformation of each word is:
“gin” -> “–…-.”
“zen” -> “–…-.”
“gig” -> “–…--.”
“msg” -> “–…--.”
There are 2 different transformations, “–…-.” and “–…--.”.

Note:

  • The length of words will be at most 100.
  • Each words[i] will have length in range [1, 12].
  • words[i] will only consist of lowercase letters.

給出了字元和MorseCode的對應關係,把相應的字串替換為MorseCode,然後去重

    public int uniqueMorseRepresentations(String[] words) {
        String[] arr = {
                ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
                ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
                "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."
        };
        Set<String> set = new HashSet<>();
        StringBuilder sb;
        for (String word : words) {
            sb = new StringBuilder();
            for (char c : word.toCharArray()) {
                sb.append(arr[c - 'a']);//每個字元都替換為相應的Morse Code
            }
            set.add(sb.toString());//去重
        }
        return set.size();
    }

905. Sort Array By Parity

Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.
Example 1:

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

給定一個數組,偶數排前面,奇數排後面

    public int[] sortArrayByParity(int[] A) {
        for (int i = 0, j = A.length - 1; i < j; ) {//從兩邊向中間遍歷
            while (i < j && A[i] % 2 == 0) i++;//從左邊開始直到遇到奇數或相遇停下
            while (i < j && A[j] % 2 == 1) j--;//從右邊開始直到遇到偶數或相遇停下
            if (i < j) {//交換
                A[i] = A[i] + A[j];
                A[j] = A[i] - A[j];
                A[i] = A[i] - A[j];
            }
        }
        return A;
    }