classSolution{public:intstrongPasswordChecker(string s){int a =0, b =0, c =0, n = s.size(), k =0;for(auto x: s){if(x >='0'&& x <='9') a =1;elseif(x >='a'&& x <='z') b =1;elseif(x >='A'&& x <='Z') c =1;}
k = a + b + c;if(n <6)returnmax(6- n,3- k);else{int p =0, del = n -20, res = del;int d[3]={0};for(int i =0; i < s.size(); i ++){int j = i;while(j < s.size()&& s[j]== s[i]) j ++;int s = j - i;
i = j -1;
p += s /3;if(s >=3) d[s %3]++;}if(n <=20)returnmax(p,3- k);if(d[0]&& del >0){int t =min(d[0], del);
del -= t;
p -= t;}if(d[1]&& del >0){int t =min(d[1]*2, del);
del -= t;
p -= t /2;}if(p && del >0){int t =min(p *3, del);
p -= t /3;}return res +max(p,3- k);}}};
publicclassSolution3{/**
* 记录连续出现的字符 起始和终止坐标
*/classSameChar{int st;int en;char c;SameChar(int st,int en,char c){this.st = st;this.en = en;this.c = c;}}publicintstrongPasswordChecker(String str){// 统计小写字符int lowerCase =0;// 统计大写字符int upwerCase =0;// 统计数字int number =0;// 统计连续字符出现的位置
java.util.ArrayList<SameChar> sameChars =newjava.util.ArrayList<SameChar>();char[] chars = str.toCharArray();if(chars.length ==0){return6;}// 记露连续出现的字符
SameChar sameChar =newSameChar(0,0,'\0');for(int i =0; i < chars.length; i++){if(chars[i]>='a'&& chars[i]<='z'){
lowerCase++;}elseif(chars[i]>='A'&& chars[i]<='Z'){
upwerCase++;}elseif(chars[i]>='0'&& chars[i]<='9'){
number++;}if(sameChar.c != chars[i]){if(sameChar.en - sameChar.st >=2){
sameChars.add(newSameChar(sameChar.st, sameChar.en, sameChar.c));}
sameChar.c = chars[i];
sameChar.st = i;
sameChar.en = i;}else{
sameChar.en = i;}}if(sameChar.en - sameChar.st >=2){
sameChars.add(newSameChar(sameChar.st, sameChar.en, sameChar.c));}// 缺失的类型. 只可能是1 or 2int needType =count0(lowerCase, upwerCase, number);// 连续的字符出现的要消除的个数 连续值-2int[] chages =newint[sameChars.size()];for(int j =0; j < sameChars.size(); j++){
chages[j]= sameChars.get(j).en - sameChars.get(j).st -1;}int res =0;// 如果长度小于6 , 很简单 要补的字符和缺失的类型择大if(str.length()<6){return Integer.max(6- str.length(), needType);}// 删除的时候 要有优先概念if(str.length()>20){int index =-1;while(needType >0&&(index =find(chages,0))>-1){
chages[index]= Integer.max(chages[index]-3,0);
res++;
needType--;}int d = str.length()-20;while(d >0&&(index =find(chages,1))>-1){
d--;
res++;
chages[index]--;}int n =0;for(int l =0; l < chages.length; l++){
n += chages[l]%3==0? chages[l]/3: chages[l]/3+1;}return res + d + needType + n;}int n =0;for(int l =0; l < chages.length; l++){
n += chages[l]%3==0? chages[l]/3: chages[l]/3+1;}return Integer.max(n, needType);}privateintcount0(int... array){int n =0;for(int i =0; i < array.length; i++){if(array[i]==0){
n++;}}return n;}privateintfind(int[] array,int n){int n0 =-1;int n1 =-1;int n2 =-1;for(int i =0; i < array.length; i++){if(array[i]>0&& array[i]%3==0){
n0 = i;}if(array[i]>0&& array[i]%3==1){
n1 = i;}if(array[i]>0&& array[i]%3==2){
n2 = i;}}if(n ==0){return n0 >-1? n0 :(n2 >-1? n2 : n1);}if(n ==1){return n1 >-1? n1 :(n2 >-1? n2 : n0);}return-1;}}
classSolution:defstrongPasswordChecker(self, s:str)->int:# 计算保持三种字符所需的替换或插入次数
min_r_or_i =3-any(c.islower()for c in s)-any(c.isupper()for c in s)-any(c.isdigit()for c in s)# 长度小于 6 时重复字串不是主导因素iflen(s)<6:returnmax(6-len(s), min_r_or_i)# 计算处理重复子串的最小次数, 替换优于插入优于删除
count =0
repeat_count ={1:0,2:0,3:0}for c, last_c inzip(s +'.','.'+ s):if c != last_c:if count >2:
repeat = count -2for i in[3,2,1]:
repeat_count[i]+= repeat // i
repeat %= i
count =0
count +=1# 长度小于等于 20 时都使用替换iflen(s)<=20:returnmax(sum(repeat_count.values()), min_r_or_i)# 长度大于 20, 考虑加入删除操作
min_remove =len(s)-20for i inrange(1,4):if min_remove > repeat_count[i]* i:
min_remove -= repeat_count[i]* i
repeat_count[i]= repeat_count[i]* i
else:
repeat_count[i]=(repeat_count[i]* i - min_remove + i -1)// i + min_remove
breakreturnmax(sum(repeat_count.values()),len(s)-20+ min_r_or_i)
funcstrongPasswordChecker(s string)int{// 统计字符类型
missTypes :=3
hasLowercase, hasUppercase, hasDigit :=false,false,false
sLen :=len(s)for_, v :=range s {if!hasLowercase && unicode.IsLower(v){
missTypes = missTypes -1
hasLowercase =true}elseif!hasUppercase && unicode.IsUpper(v){
missTypes = missTypes -1
hasUppercase =true}elseif!hasDigit && unicode.IsDigit(v){
missTypes = missTypes -1
hasDigit =true}}
steps :=0// 长度小于6的时候,优先考虑插入,优先考虑补充类型if sLen <6{if6- sLen >= missTypes {return6- sLen
}return missTypes
}elseif sLen >20{// 先使用缺失类型替换
result :=getSameCharArray(s)for{
index :=find(result,2)if missTypes <=0|| index <=-1{break}if result[index]-3>0{
result[index]= result[index]-3}else{
result[index]=0}
steps++
missTypes--}// 删除连续字符
minDelete := sLen -20for{
index :=find(result,0)if minDelete <=0|| index <=-1{
steps += minDelete
break}
minDelete--
steps++if result[index]-3>0{
result[index]= result[index]-1}else{
result[index]=0}}for_, v :=range result {
steps += v /3}return steps + missTypes
}// 6 - 20 直接考虑替换
result :=getSameCharArray(s)for_, v :=range result {
steps += v /3}if steps < missTypes {return missTypes
}return steps
}funcgetSameCharArray(s string)(result []int){
length :=0
lastIndex :=""for index, v :=range s{ifstring(v)!= lastIndex{if length >=3{
result =append(result, length)}
lastIndex =string(v)
length =1}elseif index ==len(s)-1{
length = length+1if length >=3{
result =append(result, length)}}else{
length = length +1}}return result
}funcfind(array []int, left int)int{
n0, n1, n2 :=-1,-1,-1for i :=0; i<len(array); i++{if array[i]>0&& array[i]%3==0{
n0 = i
}if array[i]>0&& array[i]%3==1{
n1 = i
}if array[i]>0&& array[i]%3==2{
n2 = i
}}// 0 > 1 > 2if left ==0{if n0 >-1{return n0
}elseif n1 >-1{return n1
}else{return n2
}}elseif left ==2{// 2 > 1 > 0if n2 >-1{return n2
}elseif n1 >-1{return n1
}else{return n0
}}return-1}
第四百二十一题:
classSolution{public:
vector<vector<int>> s;voidinsert(int x){int p =0;for(int i =30; i >=0; i --){int u = x >> i &1;if(!s[p][u]) s[p][u]= s.size(), s.push_back({0,0});
p = s[p][u];}}intquery(int x){int p =0, res =0;for(int i =30; i >=0; i --){int u = x >> i &1;if(s[p][!u]) p = s[p][!u], res = res *2+!u;else p = s[p][u], res = res *2+ u;}return res ^ x;}intfindMaximumXOR(vector<int>& nums){
s.push_back({0,0});int res =0;for(auto x: nums){
res =max(res,query(x));insert(x);}return res;}};
classSolution{publicintfindMaximumXOR(int[] nums){int maxNum = nums[0];for(int num : nums) maxNum = Math.max(maxNum, num);// length of max number in a binary representationint L =(Integer.toBinaryString(maxNum)).length();int maxXor =0, currXor;
Set<Integer> prefixes =newHashSet<>();for(int i = L -1; i >-1;--i){// go to the next bit by the left shift
maxXor <<=1;// set 1 in the smallest bit
currXor = maxXor |1;
prefixes.clear();// compute all possible prefixes // of length (L - i) in binary representationfor(int num: nums) prefixes.add(num >> i);// Update maxXor, if two of these prefixes could result in currXor.// Check if p1^p2 == currXor, i.e. p1 == currXor^p2.for(int p: prefixes){if(prefixes.contains(currXor^p)){
maxXor = currXor;break;}}}return maxXor;}}
classSolution:deffindMaximumXOR(self, nums: List[int])->int:# length of max number in a binary representation
L =len(bin(max(nums)))-2
max_xor =0for i inrange(L)[::-1]:# go to the next bit by the left shift
max_xor <<=1# set 1 in the smallest bit
curr_xor = max_xor |1# compute all existing prefixes # of length (L - i) in binary representation
prefixes ={num >> i for num in nums}# Update max_xor, if two of these prefixes could result in curr_xor.# Check if p1^p2 == curr_xor, i.e. p1 == curr_xor^p2
max_xor |=any(curr_xor^p in prefixes for p in prefixes)return max_xor
funcfindMaximumXOR(nums []int)int{
sort.Ints(nums)
maxBinStr := strconv.FormatInt(int64(nums[len(nums)-1]),2)var maxNums []int
format :="%"+ fmt.Sprintf("0%ds",len(maxBinStr))for i :=len(nums)-1; i >=0; i--{
in := fmt.Sprintf(format, strconv.FormatInt(int64(nums[i]),2))if in[0]=='1'{
maxNums =append(maxNums, nums[i])}else{break}}var result intfor_, max :=range maxNums {for_, num :=range nums {if max == num {continue}
result =int(math.Max(float64(result),float64(max^num)))}}return result
}
第四百二十三题:
classSolution{public:
string originalDigits(string s){
string name[]={"zero","one","two","three","four","five","six","seven","eight","nine"};int ord[]={0,8,3,2,6,4,5,1,7,9};
unordered_map<char,int> cnt;for(auto c: s) cnt[c]++;
string res;for(int x: ord){while(true){bool flag =true;for(auto c: name[x])if(!cnt[c]){
flag =false;break;}if(flag){
res +=to_string(x);for(auto c: name[x]) cnt[c]--;}elsebreak;}}sort(res.begin(), res.end());return res;}};
classSolution{public String originalDigits(String s){// building hashmap letter -> its frequencychar[] count =newchar[26+(int)'a'];for(char letter: s.toCharArray()){
count[letter]++;}// building hashmap digit -> its frequencyint[] out =newint[10];// letter "z" is present only in "zero"
out[0]= count['z'];// letter "w" is present only in "two"
out[2]= count['w'];// letter "u" is present only in "four"
out[4]= count['u'];// letter "x" is present only in "six"
out[6]= count['x'];// letter "g" is present only in "eight"
out[8]= count['g'];// letter "h" is present only in "three" and "eight"
out[3]= count['h']- out[8];// letter "f" is present only in "five" and "four"
out[5]= count['f']- out[4];// letter "s" is present only in "seven" and "six"
out[7]= count['s']- out[6];// letter "i" is present in "nine", "five", "six", and "eight"
out[9]= count['i']- out[5]- out[6]- out[8];// letter "n" is present in "one", "nine", and "seven"
out[1]= count['n']- out[7]-2* out[9];// building output string
StringBuilder output =newStringBuilder();for(int i =0; i <10; i++)for(int j =0; j < out[i]; j++)
output.append(i);return output.toString();}}
classSolution:deforiginalDigits(self, s:'str')->'str':# building hashmap letter -> its frequency
count = collections.Counter(s)# building hashmap digit -> its frequency
out ={}# letter "z" is present only in "zero"
out["0"]= count["z"]# letter "w" is present only in "two"
out["2"]= count["w"]# letter "u" is present only in "four"
out["4"]= count["u"]# letter "x" is present only in "six"
out["6"]= count["x"]# letter "g" is present only in "eight"
out["8"]= count["g"]# letter "h" is present only in "three" and "eight"
out["3"]= count["h"]- out["8"]# letter "f" is present only in "five" and "four"
out["5"]= count["f"]- out["4"]# letter "s" is present only in "seven" and "six"
out["7"]= count["s"]- out["6"]# letter "i" is present in "nine", "five", "six", and "eight"
out["9"]= count["i"]- out["5"]- out["6"]- out["8"]# letter "n" is present in "one", "nine", and "seven"
out["1"]= count["n"]- out["7"]-2* out["9"]# building output string
output =[key * out[key]for key insorted(out.keys())]return"".join(output)
funcoriginalDigits(s string)string{
M :=map[byte]int{}for i :=0; i <len(s); i++{
M[s[i]]++}
order :=[]byte{'z','x','w','u','g','o','t','f','s','i'}
number :=[]byte{'0','6','2','4','8','1','3','5','7','9'}
erase :=[][]byte{{'z','e','r','o'},{'s','i','x'},{'t','w','o'},{'f','o','u','r'},{'e','i','g','h','t'},{'o','n','e'},{'t','h','r','e','e'},{'f','i','v','e'},{'s','e','v','e','n'},{'n','i','n','e'},}var buf [][]bytefor i :=0; i <len(order); i++{
c := M[order[i]]var b []bytefor j :=0; j < c; j++{
b =append(b, number[i])}for j :=0; j <len(erase[i]); j++{
M[erase[i][j]]-= c
}
buf =append(buf, b)}returnstring(buf[0])+string(buf[5])+string(buf[2])+string(buf[6])+string(buf[3])+string(buf[7])+string(buf[1])+string(buf[8])+string(buf[4])+string(buf[9])}
第四百二十四题:
classSolution{public:intcharacterReplacement(string s,int k){int res =0;for(char c ='A'; c <='Z'; c ++){for(int i =0, j =0, cnt =0; i < s.size(); i ++){if(s[i]== c) cnt ++;while(i - j +1- cnt > k){if(s[j]== c) cnt --;
j ++;}
res =max(res, i - j +1);}}return res;}};
publicclassSolution{publicintcharacterReplacement(String s,int k){int len = s.length();if(len <2){return len;}char[] charArray = s.toCharArray();int left =0;int right =0;int res =0;int maxCount =0;int[] freq =newint[26];// [left, right) 内最多替换 k 个字符可以得到只有一种字符的子串while(right < len){
freq[charArray[right]-'A']++;// 在这里维护 maxCount,因为每一次右边界读入一个字符,字符频数增加,才会使得 maxCount 增加
maxCount = Math.max(maxCount, freq[charArray[right]-'A']);
right++;if(right - left > maxCount + k){// 说明此时 k 不够用// 把其它不是最多出现的字符替换以后,都不能填满这个滑动的窗口,这个时候须要考虑左边界向右移动// 移出滑动窗口的时候,频数数组须要相应地做减法
freq[charArray[left]-'A']--;
left++;}
res = Math.max(res, right - left);}return res;}}
classSolution:defcharacterReplacement(self, s:str, k:int)->int:
n_char =[0]*26
max_n =0
start =0
ret =0for end inrange(len(s)):
ind =ord(s[end])-ord('A')
n_char[ind]+=1
max_n = max_n if max_n > n_char[ind]else n_char[ind]if max_n + k < end - start +1:
n_char[ord(s[start])-ord('A')]-=1
start +=1else:
ret =max(ret, end - start +1)return ret
funccharacterReplacement(s string, k int)int{if s ==""{return0}// 左指针 / 右指针
left, right :=0,0// 最长长度 / 当前窗口所有字符计数
maxLen, m :=0,make(map[uint8]int)for right =0; right <len(s); right++{
m[s[right]]++
maxLen =max(maxLen, m[s[right]])// 当前窗口最多的字符计数// 如果窗口无法满足凑成全部一样的字符,滑动左指针if right-left+1> maxLen+k {
m[s[left]]--
left++}}returnlen(s)- left
}funcmax(a, b int)int{if a > b {return a
}return b
}
第四百二十七题:
/*
// Definition for a QuadTree node.
class Node {
public:
bool val;
bool isLeaf;
Node* topLeft;
Node* topRight;
Node* bottomLeft;
Node* bottomRight;
Node() {
val = false;
isLeaf = false;
topLeft = NULL;
topRight = NULL;
bottomLeft = NULL;
bottomRight = NULL;
}
Node(bool _val, bool _isLeaf) {
val = _val;
isLeaf = _isLeaf;
topLeft = NULL;
topRight = NULL;
bottomLeft = NULL;
bottomRight = NULL;
}
Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
val = _val;
isLeaf = _isLeaf;
topLeft = _topLeft;
topRight = _topRight;
bottomLeft = _bottomLeft;
bottomRight = _bottomRight;
}
};
*/classSolution{public:
vector<vector<int>> s;
Node*construct(vector<vector<int>>& w){int n = w.size();
s = vector<vector<int>>(n +1, vector<int>(n +1));for(int i =1; i <= n; i ++)for(int j =1; j <= n; j ++)
s[i][j]= s[i -1][j]+ s[i][j -1]- s[i -1][j -1]+ w[i -1][j -1];returndfs(1,1, n, n);}
Node*dfs(int x1,int y1,int x2,int y2){int n = x2 - x1 +1;int sum = s[x2][y2]- s[x2][y1 -1]- s[x1 -1][y2]+ s[x1 -1][y1 -1];if(sum ==0|| sum == n * n)returnnewNode(!!sum,true);auto node =newNode(0,false);int m = n /2;
node->topLeft =dfs(x1, y1, x1 + m -1, y1 + m -1);
node->topRight =dfs(x1, y1 + m, x1 + m -1, y2);
node->bottomLeft =dfs(x1 + m, y1, x2, y1 + m -1);
node->bottomRight =dfs(x1 + m, y1 + m, x2, y2);return node;}};
"""
# Definition for a QuadTree node.
class Node:
def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
self.val = val
self.isLeaf = isLeaf
self.topLeft = topLeft
self.topRight = topRight
self.bottomLeft = bottomLeft
self.bottomRight = bottomRight
"""classSolution:defconstruct(self, grid: List[List[int]])->'Node':return Node(bool(s),True)ifnot(s :=sum(map(sum, grid)))ornot(m :=len(grid)>>1)or s ==4* m * m else Node(True,False, self.construct([g[:m]for g in grid[:m]]), self.construct([g[m:]for g in grid[:m]]), self.construct([g[:m]for g in grid[m:]]), self.construct([g[m:]for g in grid[m:]]))
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/classSolution{public:
vector<vector<int>>levelOrder(Node* root){
vector<vector<int>> res;if(!root)return res;
queue<Node*> q;
q.push(root);while(q.size()){int len = q.size();
vector<int> line;while(len --){auto t = q.front();
q.pop();
line.push_back(t->val);for(auto c: t->children) q.push(c);}
res.push_back(line);}return res;}};
// This code is a modified version of the code posted by// #zzzliu on the discussion forums.classSolution{public List<List<Integer>>levelOrder(Node root){
List<List<Integer>> result =newArrayList<>();if(root == null)return result;
Queue<Node> queue =newLinkedList<>();
queue.add(root);while(!queue.isEmpty()){
List<Integer> level =newArrayList<>();int size = queue.size();for(int i =0; i < size; i++){
Node node = queue.poll();
level.add(node.val);
queue.addAll(node.children);}
result.add(level);}return result;}}
/**
* Definition for a Node.
* type Node struct {
* Val int
* Children []*Node
* }
*/var res [][]intfunclevelOrder(root *Node)[][]int{
res =[][]int{}if root ==nil{return res
}
queue :=[]*Node{root}var level intfor0<len(queue){
counter :=len(queue)
res =append(res,[]int{})for i :=0; i < counter; i++{if queue[i]!=nil{
res[level]=append(res[level], queue[i].Val)for_, n :=range queue[i].Children {
queue =append(queue, n)}}}
queue = queue[counter:]
level++}return res
}
第四百三十题:
/*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
};
*/classSolution{public:
Node*flatten(Node* head){auto res =dfs(head);return res[0];}
vector<Node*>dfs(Node* head){if(!head)return{NULL,NULL};auto cur = head, tail = head;while(cur){
tail = cur;if(cur->child){auto t =dfs(cur->child);
cur->child =NULL;
t[1]->next = cur->next;if(cur->next) cur->next->prev = t[1];
cur->next = t[0];
t[0]->prev = cur;
cur = t[1]->next;
tail = t[1];}else{
cur = cur->next;}}return{head, tail};}};
/*
// Definition for a Node.
class Node {
public int val;
public Node prev;
public Node next;
public Node child;
public Node() {}
public Node(int _val,Node _prev,Node _next,Node _child) {
val = _val;
prev = _prev;
next = _next;
child = _child;
}
};
*/classSolution{public Node flatten(Node head){if(head == null)return head;// pseudo head to ensure the `prev` pointer is never none
Node pseudoHead =newNode(0, null, head, null);flattenDFS(pseudoHead, head);// detach the pseudo head from the real head
pseudoHead.next.prev = null;return pseudoHead.next;}/* return the tail of the flatten list */public Node flattenDFS(Node prev, Node curr){if(curr == null)return prev;
curr.prev = prev;
prev.next = curr;// the curr.next would be tempered in the recursive function
Node tempNext = curr.next;
Node tail =flattenDFS(curr, curr.child);
curr.child = null;returnflattenDFS(tail, tempNext);}}
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""classSolution(object):defflatten(self, head):ifnot head:return head
# pseudo head to ensure the `prev` pointer is never none
pseudoHead = Node(None,None, head,None)
self.flatten_dfs(pseudoHead, head)# detach the pseudo head from the real head
pseudoHead.next.prev =Nonereturn pseudoHead.nextdefflatten_dfs(self, prev, curr):""" return the tail of the flatten list """ifnot curr:return prev
curr.prev = prev
prev.next= curr
# the curr.next would be tempered in the recursive function
tempNext = curr.next
tail = self.flatten_dfs(curr, curr.child)
curr.child =Nonereturn self.flatten_dfs(tail, tempNext)
/**
* Definition for a Node.
* type Node struct {
* Val int
* Prev *Node
* Next *Node
* Child *Node
* }
*/funcflatten(root *Node)*Node {if root ==nil{return root
}var cur, after *Node = root,nilfor cur !=nil{
after = cur.Next
if cur.Child !=nil{
child := cur.Child
cur.Next = child
child.Prev = cur
cur.Child =nilfor child.Next !=nil{
child = child.Next
}
child.Next = after
if after !=nil{// 需要注意这种异常情况,避免panic
after.Prev = child
}}
cur = cur.Next
}return root
}
第四百二十题:class Solution {public: int strongPasswordChecker(string s) { int a = 0, b = 0, c = 0, n = s.size(), k = 0; for (auto x: s) { if (x >= '0' && x <= '9') a = 1; else if (x >= 'a' &&