1.字符串操作
给定一个只包含小写字母字符串,每次可以选择两个相同的字符删除,并在字符串结尾新增任意一个小写字母。
请问最少多少次操作后,所有的字母都不相同?
public int minOperations (String str) {
// write code here
int[] count=new int[26];
for(char c:str.toCharArray()){
count[c-'a']++;
}
int sum=0;
int res=0;
int nocount=0;
for(int i=0;i<26;i++){
sum+=count[i]/2;
count[i]%=2;
if(count[i]==0)
nocount++;
}
if(sum<nocount) return sum;
res=sum+sum-nocount;
return res;
}
给定一棵二叉树,二叉树的每个结点只有0或2个孩子。
public int getTreeSum (TreeNode tree) {
// write code here
int ans=1,k=height(tree);
while(k>=0){
ans=ans*2;
ans%=1000000007;
k--;
}
return ans-1;
}
int height(TreeNode tree){
if(tree==null) return -1;
return 1+Math.max(height(tree.left),height(tree.right));
}
4.01串修改
给定一个只包含’0’和’1’两种字符的字符串,每次操作可以选择相邻的两个字符,将它们同时变成’0’或者同时变成’1’。
请问最少多少次操作后,所有的字符都相同?
public int minOperations (String str) {
// write code here
int num0=0,num1=0;
int i=0;
while(i<str.length()){
int st=i;
if(str.charAt(i)=='0'){
while(i<str.length()&&str.charAt(i)=='0'){
++i;
}
num0+=(i-st)/2;
num0+=(i-st)%2;
}
else{
while(i<str.length()&&str.charAt(i)=='1'){
++i;
}
num1+=(i-st)/2;
num1+=(i-st)%2;
}
}
return Math.min(num0,num1);
}