题目描述
我的代码:
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
if(ransomNote.length() > magazine.length())
return false;
if(ransomNote.equals(magazine))
return true;
char[] s1 = ransomNote.toCharArray();
char[] s2 = magazine.toCharArray();
ArrayList<Character> st1 = new ArrayList<>();
ArrayList<Character> st2 = new ArrayList<>();
for (int i = 0; i < s1.length; i++) {
char c = s1[i];
st1.add(c);
}
for (int i = 0; i < s2.length; i++) {
char c = s2[i];
st2.add(c);
}
for (int i = 0; i < ransomNote.length(); i++) {
if(st2.contains(s1[i])){
int index = st2.indexOf(s1[i]);
st2.remove(index);
}else {
return false;
}
}
return true;
}
}
自身对其进行优化,避免使用了list麻烦,直接使用数组来完成相关的操作
if(ransomNote.length() > magazine.length())
return false;
if(ransomNote.equals(magazine))
return true;
char[] s1 = ransomNote.toCharArray();
char[] s2 = magazine.toCharArray();
int [] flag = new int[256];
for (int i = 0; i < s2.length; i++) {
char c = s2[i];
flag[c]++;
}
for (int i = 0; i < s1.length; i++) {
char c = s1[i];
if(flag[c] == 0){
return false;
}else {
flag[c] --;
}
}
return true;
排名较高的代码:
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
boolean ans=true;
int[] marked=new int[123];
char[] c=magazine.toCharArray();
char[] x=ransomNote.toCharArray();
for(int i=0; i<c.length; i++){
marked[c[i]]++;
}
for(int i=0; i<x.length; i++){
if(marked[x[i]]==0){
ans=false;
break;
}
else{
marked[x[i]]--;
}
}
return ans;
}
}