leetcode869
class Solution {
public boolean reorderedPowerOf2(int N) {
long c=counter(N);
for(int i=0;i<32;i++){
if(counter(1<<i)==c)return true;
}
return false;
}
public long counter(int n){
int res=0;
for(;n>0;n/=10)res+=Math.pow(10,n%10);
return res;
}
}
这里是一种比较巧妙的计数器,做的事情是把每位数字进行了编码,使得每个数字都去了自己对应的位置
比如 1 3 3 2
编码过程:
100(Math.pow(10,2))
1000 (Math.pow(10,3))
10 (Math.pow(10,1))
所以这里就是这个样子用整数代表每一位出现的次数,由于题目说因为题目有个条件是n < 1e9
所以每个数字出现次数不会大于9
编码结果:2110
用通用一点的解法,当次数比较大的时候:这里面用":"去分割开各个位的次数,这样不管多大都ok啦,用string当作返回结果
public String counter(int n){
String temp="";
int[] c=new int[10];
int res=0;
for(;n>0;n/=10)c[n%10]++;
for(int i=0;i<10;i++)temp+=":"+c[i];
return temp;
}
leetcode 45 单词分组也可以用
class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
Map<String,List<String>>map=new HashMap<>();
for(String s:strs){
String key=counter(s);
if(!map.containsKey(key)){
map.put(key,new ArrayList<>());
}
map.get(key).add(s);
}
List<List<String>> ans=new ArrayList<>();
for(String s: map.keySet()){
ans.add(map.get(s));
}
return ans;
}
public String counter(String s){
int[] c=new int[26];
for(int i=0;i<s.length();i++){
c[s.charAt(i)-'a']++;
}
String temp="";
for(int i=0;i<26;i++)temp+=":"+c[i];
return temp;
}
}