LeetCode 389~395题

第三百八十九题

class Solution {
public:
    char findTheDifference(string s, string t) {
        int x = 0;
        for (auto c: s) x ^= c;
        for (auto c: t) x ^= c;
        return x;
    }
};
class Solution {
    public char findTheDifference(String s, String t) {
        int ret = 0;
        for (int i = 0; i < s.length(); ++i) {
            ret ^= s.charAt(i);
        }
        for (int i = 0; i < t.length(); ++i) {
            ret ^= t.charAt(i);
        }
        return (char) ret;
    }
}
class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        a = "".join([s,t])
        for ch in a:
            if a.count(ch) % 2 == 1:
                return ch
func findTheDifference(s, t string) (diff byte) {
    for i := range s {
        diff ^= s[i] ^ t[i]
    }
    return diff ^ t[len(t)-1]
}

第三百九十题

class Solution {
public:
    int lastRemaining(int n) {
        if (n == 1) return 1;
        return 2 * (n / 2 + 1 - lastRemaining(n / 2));
    }
};
class Solution {
    public int lastRemaining(int n) {
         return n == 1 ? 1 : 2 * (n / 2 + 1 - lastRemaining(n / 2));
    }
    
}
class Solution:
    def lastRemaining(self, n: int) -> int:
        return 1 if n==1 else 2*(n//2+1-self.lastRemaining(n//2))
func lastRemaining(n int) int {
	if n == 0 {
		return 0
	}
	var stack []int
	for i := 1; i <= n; i++ {
		stack = append(stack, i)
	}
	for len(stack) >= 2 {
		l := len(stack)
		var tempStack []int
		for i := 0; i < l; i ++ {
			if (l-1-i)%2 == 1 {
				tempStack = append(tempStack, stack[l-1-i])
			}
		}
		stack = tempStack
	}
	return stack[0]
}

第三百九十一题

class Solution {
public:
    bool isRectangleCover(vector<vector<int>>& r) {
        map<pair<int, int>, int> cnt;
        typedef long long LL;
        LL sum = 0;
        for (auto x: r) {
            LL a = x[0], b = x[1], c = x[2], d = x[3];
            ++ cnt[{a, b}], ++ cnt[{a, d}];
            ++ cnt[{c, b}], ++ cnt[{c, d}];
            sum += (c - a) * (d - b);
        }
        vector<vector<int>> res;
        for (auto& [x, y]: cnt)
            if (y == 1) res.push_back({x.first, x.second});
            else if (y == 3) return false;
            else if (y > 4) return false;
        if (res.size() != 4) return false;
        sort(res.begin(), res.end());
        return sum == (LL)(res[3][0] - res[0][0]) * (res[3][1] - res[0][1]);
    }
};
class Solution {
    public boolean isRectangleCover(int[][] rectangles) {
        // 完美矩形的左下角和右上角坐标
        int X1 = Integer.MAX_VALUE, Y1 = Integer.MAX_VALUE;
        int X2 = Integer.MIN_VALUE, Y2 = Integer.MIN_VALUE;
		
        // 小矩形面积之和
        int areas = 0;
        // 记录所有顶点的出现情况
        Set<String> points = new HashSet<>();
        for (int[] rectangle : rectangles) {
            int x1 = rectangle[0], y1 = rectangle[1], x2 = rectangle[2], y2 = rectangle[3];
            // 更新坐标
            X1 = Math.min(x1, X1);
            Y1 = Math.min(y1, Y1);
            X2 = Math.max(x2, X2);
            Y2 = Math.max(y2, Y2);

            areas += (x2 - x1) * (y2 - y1);
            // 判断顶点是否出现过
            String[] ps = {x1 + " " + y1, x2 + " " + y2, x1 + " " + y2, x2 + " " + y1};
            for (String s : ps) {
                // 没有出现过,添加;否则,移除
                if(points.contains(s)){
                    points.remove(s);
                } else {
                    points.add(s);
                }
            }
        }
		
        // 面积是否相等 
        int expected = (X2 - X1) * (Y2 -Y1);
        if(areas != expected){
            return false;
        }
        // 顶点情况是否满足
        if(points.size() != 4 || !points.contains(X1 + " " + Y1) || !points.contains(X2 + " " + Y2) || !points.contains(X1 + " " + Y2) || !points.contains(X2 + " " + Y1)){
            return false;
        }
        return true;
    }
}
class Solution:
    def isRectangleCover(self, rectangles: List[List[int]]) -> bool:
        m = len(rectangles)

        S = 0
        vector = set()

        for i in range(m):
            x1, y1, x2, y2 = rectangles[i]
            S += (x2 - x1) * (y2 - y1) # 当前矩形区域的计算面积,并进行统计
            for ele in [(x1, y1), (x1, y2), (x2, y1), (x2, y2)]:
                if ele in vector:
                    vector.remove(ele) # 如果有相同坐标就删除
                else:
                    vector.add(ele) # 新的坐标就添加

        vector = list(set(vector)) # 转成列表进行排序
        vector.sort()

        if len(vector) != 4: # 如果不是四个坐标说明有缺少区域
            return False

        x1, y1 = vector[0]
        x2, y2 = vector[-1]
        new_S = (x2 - x1) * (y2 - y1) # 通过排序好的坐标,取左下角和右上角的坐标,计算总面积

        if new_S == S:
            return True # 面积相同则精准覆盖
        else:
            return False
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func isRectangleCover(rectangles [][]int) bool {
	pos1 := math.MaxInt32
	pos2 := math.MaxInt32
	pos3 := math.MinInt32
	pos4 := math.MinInt32
	area := 0
	set := map[int]bool{}
	for _, rect := range rectangles {
		pos1 = min(pos1, rect[0])
		pos2 = min(pos2, rect[1])
		pos3 = max(pos3, rect[2])
		pos4 = max(pos4, rect[3])
		area += (rect[2] - rect[0]) * (rect[3] - rect[1])
		setPut(set, rect[0], rect[1])
		setPut(set, rect[0], rect[3])
		setPut(set, rect[2], rect[3])
		setPut(set, rect[2], rect[1])
	}
	if (pos3-pos1)*(pos4-pos2) != area {
		return false
	}

	if len(set) != 4 {
		return false
	}

	if set[pos1*10000000+pos2] && set[pos1*10000000+pos4] && set[pos3*10000000+pos4] && set[pos3*10000000+pos2] {
		return true
	}
	return false
}
func setPut(set map[int]bool, x, y int) {
	if set[x*10000000+y]{
		delete(set,x*10000000+y)
	} else{
		set[x*10000000+y]=true
	}
}

第三百九十二题

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int k = 0;
        for (auto c: t)
            if (k < s.size() && c == s[k])
                k ++ ;
        return k == s.size();
    }
};
class Solution {
    public boolean isSubsequence(String s, String t) {
        int n = s.length(), m = t.length();
        int i = 0, j = 0;
        while (i < n && j < m) {
            if (s.charAt(i) == t.charAt(j)) {
                i++;
            }
            j++;
        }
        return i == n;
    }
}
class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        n, m = len(s), len(t)
        i = j = 0
        while i < n and j < m:
            if s[i] == t[j]:
                i += 1
            j += 1
        return i == n
func isSubsequence(s string, t string) bool {
    n, m := len(s), len(t)
    i, j := 0, 0
    for i < n && j < m {
        if s[i] == t[j] {
            i++
        }
        j++
    }
    return i == n
}

第三百九十三题

class Solution {
public:
    int get(int x, int k) {
        return x >> k & 1;
    }

    bool validUtf8(vector<int>& data) {
        for (int i = 0; i < data.size(); i ++ ) {
            if (!get(data[i], 7)) continue;
            int k = 0;
            while (k <= 4 && get(data[i], 7 - k)) k ++ ;
            if (k == 1 || k > 4) return false;
            for (int j = 0; j < k - 1; j ++ ) {
                int t = i + 1 + j;
                if (t >= data.size()) return false;
                if (!(get(data[t], 7) && !get(data[t], 6))) return false;
            }
            i += k - 1;
        }
        return true;
    }
};
class Solution {
  public boolean validUtf8(int[] data) {

    // Number of bytes in the current UTF-8 character
    int numberOfBytesToProcess = 0;

    // For each integer in the data array.
    for (int i = 0; i < data.length; i++) {

      // Get the binary representation. We only need the least significant 8 bits
      // for any given number.
      String binRep = Integer.toBinaryString(data[i]);
      binRep =
          binRep.length() >= 8
              ? binRep.substring(binRep.length() - 8)
              : "00000000".substring(binRep.length() % 8) + binRep;

      // If this is the case then we are to start processing a new UTF-8 character.
      if (numberOfBytesToProcess == 0) {

        // Get the number of 1s in the beginning of the string.
        for (int j = 0; j < binRep.length(); j++) {
          if (binRep.charAt(j) == '0') {
            break;
          }

          numberOfBytesToProcess += 1;
        }

        // 1 byte characters
        if (numberOfBytesToProcess == 0) {
          continue;
        }

        // Invalid scenarios according to the rules of the problem.
        if (numberOfBytesToProcess > 4 || numberOfBytesToProcess == 1) {
          return false;
        }

      } else {

        // Else, we are processing integers which represent bytes which are a part of
        // a UTF-8 character. So, they must adhere to the pattern `10xxxxxx`.
        if (!(binRep.charAt(0) == '1' && binRep.charAt(1) == '0')) {
          return false;
        }
      }

      // We reduce the number of bytes to process by 1 after each integer.
      numberOfBytesToProcess -= 1;
    }

    // This is for the case where we might not have the complete data for
    // a particular UTF-8 character.
    return numberOfBytesToProcess == 0;
  }
}
class Solution:
    def validUtf8(self, data):
        """
        :type data: List[int]
        :rtype: bool
        """

        # Number of bytes in the current UTF-8 character
        n_bytes = 0

        # For each integer in the data array.
        for num in data:

            # Get the binary representation. We only need the least significant 8 bits
            # for any given number.
            bin_rep = format(num, '#010b')[-8:]

            # If this is the case then we are to start processing a new UTF-8 character.
            if n_bytes == 0:

                # Get the number of 1s in the beginning of the string.
                for bit in bin_rep:
                    if bit == '0': break
                    n_bytes += 1

                # 1 byte characters
                if n_bytes == 0:
                    continue

                # Invalid scenarios according to the rules of the problem.
                if n_bytes == 1 or n_bytes > 4:
                    return False
            else:
                # Else, we are processing integers which represent bytes which are a part of
                # a UTF-8 character. So, they must adhere to the pattern `10xxxxxx`.
                if not (bin_rep[0] == '1' and bin_rep[1] == '0'):
                    return False

            # We reduce the number of bytes to process by 1 after each integer.
            n_bytes -= 1

        # This is for the case where we might not have the complete data for
        # a particular UTF-8 character.
        return n_bytes == 0     

func validUtf8(data []int) bool {

    getCount := func(b int) int {
        count := 0
        switch {
        case b >> 3 == 0b11110:
            count = 4
        case b >> 4 == 0b1110:
            count = 3
        case b >> 5 == 0b110:
            count = 2
        case b >> 7 == 0b0:
            count = 1
        default:
            count = -2
        }
        return count
    }

    count := 0
    for _, b := range data {
        if count == 0 {
            count = getCount(b)
            if count < 0 {
                return false
            }
        } else {
            if !(b >> 6 == 0b10) {
                return false
            }
        }
        count--
    } 

    return count==0
}

第三百九十四题

class Solution {
public:
    string decodeString(string s) {
        int u = 0;
        return dfs(s, u);
    }

    string dfs(string& s, int& u) {
        string res;
        while (u < s.size() && s[u] != ']') {
            if (s[u] >= 'a' && s[u] <= 'z' || s[u] >= 'A' && s[u] <= 'Z') res += s[u ++ ];
            else if (s[u] >= '0' && s[u] <= '9') {
                int k = u;
                while (s[k] >= '0' && s[k] <= '9') k ++ ;
                int x = stoi(s.substr(u, k - u));
                u = k + 1;
                string y = dfs(s, u);
                u ++ ; // 过滤掉右括号
                while (x -- ) res += y;
            }
        }
        return res;
    }
};
class Solution {
    int ptr;

    public String decodeString(String s) {
        LinkedList<String> stk = new LinkedList<String>();
        ptr = 0;

        while (ptr < s.length()) {
            char cur = s.charAt(ptr);
            if (Character.isDigit(cur)) {
                // 获取一个数字并进栈
                String digits = getDigits(s);
                stk.addLast(digits);
            } else if (Character.isLetter(cur) || cur == '[') {
                // 获取一个字母并进栈
                stk.addLast(String.valueOf(s.charAt(ptr++))); 
            } else {
                ++ptr;
                LinkedList<String> sub = new LinkedList<String>();
                while (!"[".equals(stk.peekLast())) {
                    sub.addLast(stk.removeLast());
                }
                Collections.reverse(sub);
                // 左括号出栈
                stk.removeLast();
                // 此时栈顶为当前 sub 对应的字符串应该出现的次数
                int repTime = Integer.parseInt(stk.removeLast());
                StringBuffer t = new StringBuffer();
                String o = getString(sub);
                // 构造字符串
                while (repTime-- > 0) {
                    t.append(o);
                }
                // 将构造好的字符串入栈
                stk.addLast(t.toString());
            }
        }

        return getString(stk);
    }

    public String getDigits(String s) {
        StringBuffer ret = new StringBuffer();
        while (Character.isDigit(s.charAt(ptr))) {
            ret.append(s.charAt(ptr++));
        }
        return ret.toString();
    }

    public String getString(LinkedList<String> v) {
        StringBuffer ret = new StringBuffer();
        for (String s : v) {
            ret.append(s);
        }
        return ret.toString();
    }
}
class Solution:
    def decodeString(self, s: str) -> str:
        stack, res, multi = [], "", 0
        for c in s:
            if c == '[':
                stack.append([multi, res])
                res, multi = "", 0
            elif c == ']':
                cur_multi, last_res = stack.pop()
                res = last_res + cur_multi * res
            elif '0' <= c <= '9':
                multi = multi * 10 + int(c)            
            else:
                res += c
        return res
func decodeString(s string) string {
    stk := []string{}
    ptr := 0
    for ptr < len(s) {
        cur := s[ptr]
        if cur >= '0' && cur <= '9' {
            digits := getDigits(s, &ptr)
            stk = append(stk, digits)
        } else if (cur >= 'a' && cur <= 'z' || cur >= 'A' && cur <= 'Z') || cur == '[' {
            stk = append(stk, string(cur))
            ptr++
        } else {
            ptr++
            sub := []string{}
            for stk[len(stk)-1] != "[" {
                sub = append(sub, stk[len(stk)-1])
                stk = stk[:len(stk)-1]
            }
            for i := 0; i < len(sub)/2; i++ {
                sub[i], sub[len(sub)-i-1] = sub[len(sub)-i-1], sub[i]
            }
            stk = stk[:len(stk)-1]
            repTime, _ := strconv.Atoi(stk[len(stk)-1])
            stk = stk[:len(stk)-1]
            t := strings.Repeat(getString(sub), repTime)
            stk = append(stk, t)
        }
    }
    return getString(stk)
}

func getDigits(s string, ptr *int) string {
    ret := ""
    for ; s[*ptr] >= '0' && s[*ptr] <= '9'; *ptr++ {
        ret += string(s[*ptr])
    }
    return ret
}

func getString(v []string) string {
    ret := ""
    for _, s := range v {
        ret += s
    }
    return ret
}

第三百九十五题

class Solution {
public:
    int K;
    unordered_map<char, int> cnt;

    void add(char c, int& x, int& y) {
        if (!cnt[c]) x ++ ;
        cnt[c] ++ ;
        if (cnt[c] == K) y ++ ;
    }

    void del(char c, int& x, int& y) {
        if (cnt[c] == K) y -- ;
        cnt[c] -- ;
        if (!cnt[c]) x -- ;
    }

    int longestSubstring(string s, int _K) {
        K = _K;
        int res = 0;
        for (int k = 1; k <= 26; k ++ ) {
            cnt.clear();
            for (int i = 0, j = 0, x = 0, y = 0; i < s.size(); i ++ ) {
                add(s[i], x, y);
                while (x > k) del(s[j ++ ], x, y);
                if (x == y) res = max(res, i - j + 1);
            }
        }
        return res;
    }
};
class Solution {
    public int longestSubstring(String s, int k) {
        int ret = 0;
        int n = s.length();
        for (int t = 1; t <= 26; t++) {
            int l = 0, r = 0;
            int[] cnt = new int[26];
            int tot = 0;
            int less = 0;
            while (r < n) {
                cnt[s.charAt(r) - 'a']++;
                if (cnt[s.charAt(r) - 'a'] == 1) {
                    tot++;
                    less++;
                }
                if (cnt[s.charAt(r) - 'a'] == k) {
                    less--;
                }

                while (tot > t) {
                    cnt[s.charAt(l) - 'a']--;
                    if (cnt[s.charAt(l) - 'a'] == k - 1) {
                        less++;
                    }
                    if (cnt[s.charAt(l) - 'a'] == 0) {
                        tot--;
                        less--;
                    }
                    l++;
                }
                if (less == 0) {
                    ret = Math.max(ret, r - l + 1);
                }
                r++;
            }
        }
        return ret;
    }
}
class Solution(object):
    def longestSubstring(self, s, k):
        if len(s) < k:
            return 0
        for c in set(s):
            if s.count(c) < k:
                return max(self.longestSubstring(t, k) for t in s.split(c))
        return len(s)
func longestSubstring(s string, k int) (ans int) {
    for t := 1; t <= 26; t++ {
        cnt := [26]int{}
        total := 0
        lessK := 0
        l := 0
        for r, ch := range s {
            ch -= 'a'
            if cnt[ch] == 0 {
                total++
                lessK++
            }
            cnt[ch]++
            if cnt[ch] == k {
                lessK--
            }

            for total > t {
                ch := s[l] - 'a'
                if cnt[ch] == k {
                    lessK++
                }
                cnt[ch]--
                if cnt[ch] == 0 {
                    total--
                    lessK--
                }
                l++
            }
            if lessK == 0 {
                ans = max(ans, r-l+1)
            }
        }
    }
    return ans
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不能say的秘密

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值