1. 程式人生 > 其它 >2021-7-7 LeetCode

2021-7-7 LeetCode

額。7.6鴿了一天,7.7也就水了四個簡單的題。嗐,我怎麼這麼懶

反轉字串

344. 反轉字串 - 力扣(LeetCode) (leetcode-cn.com)

編寫一個函式,其作用是將輸入的字串反轉過來。

不要給另外的陣列分配額外的空間,你必須原地修改輸入陣列、使用 O(1) 的額外空間解決這一問題。

輸入:["h","e","l","l","o"]
輸出:["o","l","l","e","h"]

程式碼:

public void reverseString(char[] s) {
    int last = s.length - 1;
    for (int i = 0; i < s.length / 2; i++)  {
        char tmp = s[i];
        s[i] = s[last];
        s[last--] = tmp;
    }
}

效率還行

反轉字串中的單詞 III

557. 反轉字串中的單詞 III - 力扣(LeetCode) (leetcode-cn.com)

給定一個字串,你需要反轉字串中每個單詞的字元順序,同時仍保留空格和單詞的初始順序。

輸入:"Let's take LeetCode contest"
輸出:"s'teL ekat edoCteeL tsetnoc"

我的思路:

public String reverseWords(String s) {
    char[] res = s.toCharArray();
    int idx = 0;	// 當前單詞的首字母索引
    for (int i = 0; i < res.length; i++) {
        if (i == res.length - 1 || res[i+1] == ' ') {
            int k = i;
            // 反轉單詞, j - idx + 1為單詞長度
            for (int j = idx; j <= (i + idx) / 2; j++) {
                // 交換
                char tmp = res[j];
                res[j] = res[k];
                res[k--] = tmp;
            }
            i++;    // 跳過空格
            idx = i + 1;	// 更新為新的單詞的首字母索引
        }
    }
    return String.copyValueOf(res);
}

看了一下題解,我這方法好像效率還可以。

刪除連結串列中的節點

237. 刪除連結串列中的節點 - 力扣(LeetCode) (leetcode-cn.com)

額。。。這道題描述給我看懵了。看程式碼吧,沒啥意思

public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
}

2的冪

231. 2 的冪 - 力扣(LeetCode) (leetcode-cn.com)

使用迴圈版:

public static boolean isPowerOfTwo(int n) {
    if (n <= 0)
        return false;
    while(n != 1) {
        if (n % 2 != 0)
            return false;
        n /= 2;
    }
    return true;
}

不使用迴圈版:

    public boolean isPowerOfTwo(int n) {
        if (n == 1)
            return true;
        if (n % 2 != 0 || n <= 0)
            return false;
        String bin = Integer.toBinaryString(n);
        return Integer.parseInt(bin.substring(1), 2) == 0;
    }

想到了用二進位制來判斷,如為2的冪,則必滿足首位為1,其餘為0.但由於對位運算不太熟,用了比較蠢的方法,把整數轉為二進位制,再把去掉第一位的二進位制串轉回來,看是否等於0.

看了下題解,突然明白,用位運算直接用n & (n-1)就行了,舉個例子,n=100, n-1=011,做與運算則為0。

嗐,找時間好好學學位運算。

public boolean isPowerOfTwo(int n) {
    return n > 0 && (n & (n-1)) == 0;
}