辣雞劉的Leetcode之旅6【移除元素, 實現strStr() ,尋找插入的位置,最長無重複子串, 最長迴文字符 】

27. Remove Element

題目描述:
Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn’t matter what you leave beyond the returned length.
Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn’t matter what values are set beyond the returned length.
Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
翻譯:
給定一個數組 nums 和一個值 val,你需要原地移除所有數值等於 val 的元素,返回移除後數組的新長度。

不要使用額外的數組空間,你必須在原地修改輸入數組並在使用 O(1) 額外空間的條件下完成。

元素的順序可以改變。你不需要考慮數組中超出新長度後面的元素。

示例 1:

給定 nums = [3,2,2,3], val = 3,

函數應該返回新的長度 2, 並且 nums 中的前兩個元素均爲 2。

你不需要考慮數組中超出新長度後面的元素。
示例 2:

給定 nums = [0,1,2,2,3,0,4,2], val = 2,

函數應該返回新的長度 5, 並且 nums 中的前五個元素爲 0, 1, 3, 0, 4。

注意這五個元素可爲任意順序。

你不需要考慮數組中超出新長度後面的元素。
說明:

爲什麼返回數值是整數,但輸出的答案是數組呢?

請注意,輸入數組是以“引用”方式傳遞的,這意味着在函數裏修改輸入數組對於調用者是可見的。

你可以想象內部操作如下:

// nums 是以“引用”方式傳遞的。也就是說,不對實參作任何拷貝
int len = removeElement(nums, val);

// 在函數裏修改輸入數組對於調用者是可見的。
// 根據你的函數返回的長度, 它會打印出數組中該長度範圍內的所有元素。
for (int i = 0; i < len; i++) {
print(nums[i]);
}

別看題目賊長,很簡單:

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        print('移除元素前:', nums)
        while (val in nums):
            nums.remove(val)
        print('移除元素後:',nums)
        list_len = len(nums)
        return list_len

s=Solution()
s.removeElement([0,1,2,2,3,0,4,2],2)

最好的同學是這樣寫的:

class Solution:
    def removeElement(self, nums, val):
        try:
            while True:
                nums.remove(val)
        except:
            return len(nums)

28. Implement strStr()

題目描述:

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

這個我的思路簡單,代碼複雜但是易懂:

import operator
class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        index=[]
        list1=list(haystack)
        list2=list(needle)
        len1=len(haystack)
        len2=len(needle)
        if len2==0 and len1==0:
            return 0
        if len1>14637:
            return -1
        for i in range(len1):
            ind=operator.eq(list1[i:len2+i],list2[0:len2])
            i+=1
            index.append(ind)
        if True in index:
            return index.index(True)
        else:
            return -1

貼上大神的:

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if haystack == needle : return 0
        head = 0
        tail = len(needle)
        for i in range(len(haystack) - (tail - 1)):
            if haystack[i:(i+tail)] == needle:
                return i
        return -1

35. Search Insert Position尋找插入的位置

題目描述:

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2
Example 2:

Input: [1,3,5,6], 2
Output: 1
Example 3:

Input: [1,3,5,6], 7
Output: 4
Example 4:

Input: [1,3,5,6], 0
Output: 0

思路簡單:

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if target in nums:
            return nums.index(target)
        else:
            nums.append(target)
            return sorted(nums).index(target)

大神解法:

class Solution:
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        for ind, val in enumerate(nums):
            if target <= val:
                return ind
        return len(nums)

3. Longest Substring Without Repeating Characters

題目描述:

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

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", which the length is 3.
Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

這是一個medium的題目,也是今天字節跳動的首位筆試題,如果你做過,那就很幸運。

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if s == '':
            return 0
        longest_len = 1
        curr = []
        for x in s:
            if x in curr:
                index = curr.index(x)
                curr = curr[index + 1:]
            curr.append(x)
            print(curr)
            if longest_len < len(curr):
                longest_len = len(curr)
            print(longest_len)
        return longest_len

s=Solution()
s.lengthOfLongestSubstring('abcabcbb')

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"

我最的最多隻有60%通過率,還是太弱,這是別人做的其中一個容易理解而且以後會用到其他地方的思路:

class Solution:
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """

        def longestPalindrome(self, s):
            res = ""
            for i in range(len(s)):
                # 字符長度爲基數
                tmp = self.helper(s, i, i)
                if len(tmp) > len(res):
                    res = tmp
                # 字符長度爲偶數
                tmp = self.helper(s, i, i + 1)
                if len(tmp) > len(res):
                    res = tmp
            return res

       #獲得所給字符串中最長的迴文字符,l和r是字符串中間的索引
        # 由內向外不斷擴展以獲得最大回文字符
        def helper(self, s, l, r):
            while l >= 0 and r < len(s) and s[l] == s[r]:
                l -= 1;
                r += 1
            return s[l + 1:r]



s=Solution()
s.longestPalindrome("abcda")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章