美文网首页
LeetCode Solution comp

LeetCode Solution comp

作者: NoneLand | 来源:发表于2018-05-17 16:53 被阅读24次

833

class Solution(object):
    def findReplaceString(self, S, indexes, sources, targets):
        S = list(S)
        for i, x, y in sorted(zip(indexes, sources, targets), reverse = True):
            if all(i+k < len(S) and S[i+k] == x[k] for k in xrange(len(x))):
                S[i:i+len(x)] = list(y)

        return "".join(S)

Mine:

class Solution:
    def findReplaceString(self, S, indexes, sources, targets):
        res = ''
        cur = 0
        inds = indexes[:]
        while indexes:
            ind = min(indexes)
            i = inds.index(ind)
            res += S[cur:ind]
            if S[ind:].startswith(sources[i]):
                res += targets[i]
                cur = ind+len(sources[i])
            else:
                cur = ind
            indexes.remove(ind)
        res += S[cur:]
        return res

亮点:使用sorted(zip(indexes, sources, targets), reverse = True)进行组合排序。使得我自己的繁琐操作得到简化。

835

image.png
class Solution:
    def largestOverlap(self, A, B):
        """
        :type A: List[List[int]]
        :type B: List[List[int]]
        :rtype: int
        """
        n = len(A)
        Max = 0
        if n > 1:
            for rt in range(n):
                for dt in range(n):
                    t = 0
                    for i in range(n):
                        for j in range(n):
                            t += A[i][j]*B[(i+dt)%n][(j+rt)%n]
                    #print(t)
                    Max = max(t, Max)
        else:
            Max = A[0][0]*B[0][0]
        return Max
class Solution(object):
    def largestOverlap(self, A, B):
        N = len(A)
        count = collections.Counter()
        for i, row in enumerate(A):
            for j, v in enumerate(row):
                if v:
                    for i2, row2 in enumerate(B):
                        for j2, v2 in enumerate(row2):
                            if v2:
                                count[i-i2, j-j2] += 1
        return max(count.values() or [0])

学习此处collections.Counter()的用法

3

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        cur = 0
        cnt = 0
        d = {}
        for i, ch in enumerate(s):
            t = d.get(ch, 0)
            if t>cur:
                cur = t
            d[ch] = i+1
            cnt = max(cnt, i+1-cur)
                
        return cnt

7

int reverse(int x) {
    int y=0;
    int n;
    while( x != 0){
        n = x%10;
        if (y > INT_MAX/10 || y < INT_MIN/10){
             return 0;
        }
        y = y*10 + n;
        x /= 10;
    }
    return y;
}

相关文章

网友评论

      本文标题:LeetCode Solution comp

      本文链接:https://www.haomeiwen.com/subject/owaddftx.html