LeetCodeContest week140

主要是引用第一名(python),第二名(python)和第五名(java)的代码

1.Occurrences After Bigram

Given words first and second, consider occurrences in some text of the form “first second third”, where second comes immediately after first, and third comes immediately after second.

For each such occurrence, add “third” to the answer, and return the answer.

Example 1:

Input: text = "alice is a good girl she is a good student", first = "a", second = "good"
Output: ["girl","student"]

Example 2:

Input: text = "we will we will rock you", first = "we", second = "will"
Output: ["we","rock"]

第一名的code: 不需要考虑越界!

class Solution:
    def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
        ws = text.split()
        return [ws[i + 2] for i in range(len(ws) - 2) if ws[i] == first and ws[i + 1] == second]

2.Letter Tile Possibilities

You have a set of tiles, where each tile has one letter tiles[i] printed on it. Return the number of possible non-empty sequences of letters you can make.

Example 1:

Input: "AAB"
Output: 8
Explanation: The possible sequences are "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA".

Example 2:

Input: "AAABBC"
Output: 188

第一名的code:

class Solution:
    def numTilePossibilities(self, tiles: str) -> int:
        permus = set()
        for i in range(1, len(tiles) + 1):
            permus |= set(itertools.permutations(tiles, i))
        return len(permus)
itertools.permutations(iterable[, r])  
Return successive r length permutations of elements in the iterable.
							排列
If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.
第二的code,思路代码类似
class Solution(object):
    def numTilePossibilities(self, tiles):
        """
        :type tiles: str
        :rtype: int
        """
        s = set()
        self.helper('', tiles, s)
        rtn = 0
        for x in s:
            if x:
                rtn += 1
        return rtn
        
    def helper(self, sofar, tiles, s):
        s.add(sofar)
        # Consider all possible choices
        n = len(tiles)
        for i in range(n):
            tmp = tiles[i]
            tiles = tiles[:i] + tiles[i+1:]
            self.helper(sofar + tmp, tiles, s)
            tiles = tiles[:i]+tmp+tiles[i:]
class Solution {
     
		
		Set<String> set = new HashSet<>();
		
	    public int numTilePossibilities(String tiles) {
     
	    	char[] s = tiles.toCharArray();
	    	dfs(s, 0, "");
	    	return set.size()-1;
	    }
	    
	    void dfs(char[] s, int ptn, String cur)
	    {
     
	    	set.add(cur);
	    	for(int i = 0;i < s.length;i++){
     
	    		if(ptn<<~i>=0){
     
	    			dfs(s, ptn|1<<i, cur + s[i]);
	    		}
	    	}
	    }
	}	

// a << ~i 等价于  a << 32 -i -1
// 应该是做题的经验,经常写这种遍历

3.Insufficient Nodes in Root to Leaf Paths

Given the root of a binary tree, consider all root to leaf paths: paths from the root to any leaf. (A leaf is a node with no children.)

A node is insufficient if every such root to leaf path intersecting this node has sum strictly less than limit.

Delete all insufficient nodes simultaneously, and return the root of the resulting binary tree.

Example 1:

Input: root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1

Output: [1,2,3,4,null,null,7,8,9,null,14]

Example 2:

Input: root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22

Output: [5,4,8,11,null,17,4,7,null,null,null,5]

第一名的code:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode:
        def post_order(node, limit):
            if node:
                node.left, l_mx = post_order(node.left, limit - node.val)
                node.right, r_mx = post_order(node.right, limit - node.val)
                mx = node.val + max(l_mx, r_mx)
                if mx >= limit:
                    return node, mx
                else:
                    return None, mx
            else:
                return None, 0
        ans, _ = post_order(root, limit)
        return ans
class Solution(object):
    def sufficientSubset(self, root, limit):
        """
        :type root: TreeNode
        :type limit: int
        :rtype: TreeNode
        """
        return self.helper(root, limit)
    
    def helper(self, node, limit):
        if not node: return None
        if not node.left and not node.right:
            if node.val < limit:
                return None
            else:
                return node
        left = self.helper(node.left, limit - node.val)
        right = self.helper(node.right, limit - node.val)
        if not left and not right:
            return None
        else:
            node.left = left
            node.right = right
            return node
        

	class Solution {
     
	    public TreeNode sufficientSubset(TreeNode root, int limit) {
     
	        if(dfs(root, limit, 0)){
     
	        	return root;
	        }else{
     
	        	return null;
	        }
	    }
	    
	    boolean dfs(TreeNode cur, int lim, int sum)
	    {
     
	    	if(cur == null)return false;
	    	sum += cur.val;
	    	if(cur.left == null && cur.right == null){
     
	    		return sum >= lim;
	    	}
	    	
	    	boolean L = dfs(cur.left, lim, sum);
	    	boolean R = dfs(cur.right, lim, sum);
	    	if(!L){
     
	    		cur.left = null;
	    	}
	    	if(!R){
     
	    		cur.right = null;
	    	}
	    	return L || R;
	    }
	}

4.Smallest Subsequence of Distinct Characters

Return the lexicographically smallest subsequence of text that contains all the distinct characters of text exactly once.

Example 1:

Input: "cdadabcc"
Output: "adbc"

Example 2:

Input: "abcd"
Output: "abcd"

Example 3:

Input: "ecbacba"
Output: "eacb"

Example 4:

Input: "leetcode"
Output: "letcod"

第一名的code:

class Solution:
    def smallestSubsequence(self, text: str) -> str:
        text = tuple(map(ord, text))
        right = {
     num : i for i, num in enumerate(text)}
        seen = set()
        stack = []
        for i, num in enumerate(text):
            if num not in seen:
                while stack and num < stack[-1] and right[stack[-1]] > i:
                    seen.remove(stack.pop())
                stack.append(num)
                seen.add(num)
        return ''.join(map(chr, stack))
        
class Solution(object):
    def smallestSubsequence(self, text):
        """
        :type text: str
        :rtype: str
        """
        chars = set()
        for c in text: chars.add(c)
        w = len(chars)
        rtn = ''
        min_index = 0
        n = len(text)
        for i in range(w):
            # dp[j] stores number of elements in chars.
            dp = [0] * n
            running_set = set()
            for j in range(n - 1, -1, -1):
                if text[j] in chars:
                    running_set.add(text[j])
                dp[j] = len(running_set)
            # Choose one index each time.
            to_choose = -1
            for j in range(min_index, n):
                if text[j] in chars and (to_choose == -1 or text[j] < text[to_choose]) and dp[j] >= len(chars):
                    to_choose = j
            rtn += text[to_choose]
            chars.remove(text[to_choose])
            min_index = to_choose + 1
        return rtn
class Solution {
     
	    public String smallestSubsequence(String text) {
     
	        char[] s = text.toCharArray();
	        int ptn = 0;
	        for(char c : s)ptn |= 1<<c-'a';
	        int n = s.length;
	        
	        char[] ret = new char[26];
	        int cur = 0;
	        int pos = -1;
	        
	        int[] cum = new int[n+1];
	        for(int i = n-1;i >= 0;i--){
     
	        	cum[i] = cum[i+1] | 1<<s[i]-'a';
	        }
	        
	        outer:
	        for(int p = 0;p < 26;p++){
     
		        for(int i = 0;i < 26;i++){
     
		        	if(cur<<~i>=0){
     
			        	for(int j = pos+1;j < n;j++){
     
			        		if(s[j]-'a' == i){
     
			        			int nex = cur|cum[j];
			        			if(nex == ptn){
     
			        				ret[p] = (char)('a'+i);
			        				pos = j;
			        				cur |= 1<<i;
			        				continue outer;
			        			}
			        		}
			        	}
		        	}
		        }
		        ret = Arrays.copyOf(ret, p);
		        break;
	        }
	        return new String(ret);
	    }
	}

你可能感兴趣的:(机器学习,算法,leetcode)