有人问:
求第一个无重复字符,如"total"的第一个无重复字符是o,"teeter"的第一个无重复字符是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; } } } }这就是面向对象的强大威力!
