面接問題文字統計
質問があります.
第1個の重複していない文字を求めて、例えば“total”の第1個の重複していない文字はoで、“teeter”の第1個の重複していない文字はrで、効率はO(nの平方)public static Character FirstNonRepeated(String)より優れます
正直に言うと、このような文字列統計の法則(何が文字の出現回数で並べられているのかなど)の問題は、筆記試験の問題ではしばしば見られ、フォーラムではいつも質問されています.筆記試験は肝心で、筆記試験はだめで、大企業は考えないでください.この中にはいろいろな方法がありますが、私にはオブジェクト向けの方法があります.このような問題を解くことができます.
これが対象に向けた威力!
第1個の重複していない文字を求めて、例えば“total”の第1個の重複していない文字はoで、“teeter”の第1個の重複していない文字はrで、効率はO(nの平方)public static Character FirstNonRepeated(String)より優れます
正直に言うと、このような文字列統計の法則(何が文字の出現回数で並べられているのかなど)の問題は、筆記試験の問題ではしばしば見られ、フォーラムではいつも質問されています.筆記試験は肝心で、筆記試験はだめで、大企業は考えないでください.この中にはいろいろな方法がありますが、私にはオブジェクト向けの方法があります.このような問題を解くことができます.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
public class Tongji {
/**
* @param args
*/
char ch;
int count = 1;
int index;
public Tongji(char ch, int index) {
this.ch = ch;
this.index = index;
}
@Override
public int hashCode() {//eclipse
final int PRIME = 31;
int result = 1;
result = PRIME * result + ch;
result = PRIME * result + count;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Tongji other = (Tongji) obj;
if (ch != other.ch)
return false;
if (count == other.count) {
other.count++;
}
return true;
}
public static void main(String[] args) {
String a = "total";
HashSet set = new HashSet();
for (int i = 0, k = a.length(); i < k; i++) {
set.add(new Tongji(a.charAt(i), i));
}
List list = new ArrayList(set);
Collections.sort(list, new Comparator() {//
public int compare(Object o1, Object o2) {
Tongji t1 = (Tongji) o1;
Tongji t2 = (Tongji) o2;
if (t1.index > t2.index)
return 1;
return 0;
}
});
for (Iterator it = list.iterator(); it.hasNext();) {
Tongji tj = (Tongji) it.next();
if (tj.count == 1) {
System.out.println("char:" + tj.ch + " count:" + tj.count);
break;
}
}
}
}
これが対象に向けた威力!