最簡單的方案,放到LinkedHashSet()再輸出出來,絕對的有序且去重,時間複雜度不高,hashset底層用的HashMap(),增加元素時間複雜度O(1)——O(n)
代碼:ps:爲了方便測試我把參數寫到了方法裏面
@Test
public void ceshi(){
String a = "AAABBDFDAC";
Set set = new LinkedHashSet();
char[] chars = a.toCharArray();
for(int i = 0 ; i < a.length() ; i ++){
set.add(chars[i]);
}
System.out.println(set.toString());;
}
時間複雜度最好的方案,而且不使用別人的東西
假定字符串是從鍵盤輸入的,就逃不出26個字母和各種標點符號範疇,可以從編碼格式角度出發,首先打印出200以內所有的字符,數字轉字符看一下有哪些
代碼:
@Test
public void ceshi2(){
String a = "AAABBDFDAC";
int i = 0;
while(i<100){
System.out.print(i+":");
System.out.print((char)i);
System.out.print(" ");
i++;
}
}
大概從33開始有東西是個!
截止到126左右,後面就沒有鍵盤上正常的字符了。
搞個150長的int空數組置爲0;
遍歷字符,根據字符ascii碼10進制數代表數組下標,拿到一個碼就在數組該下標位置裏的值執行加一操作,如果加完1以後是1就放到StringBuffer裏面。最後輸出字符串。(事實上還帶了統計重複出現次數的功能,但是不支持中文等,只支持普通字符)
150的數組可能有點浪費內存
@Test
public void ceshi2(){
String a = "AAABBccDFDACggghh";
int [] table = new int[150];
StringBuffer sb = new StringBuffer();
char[] chars = a.toCharArray();
for (int i = 0 ; i < chars.length ;i++){
int flag = (int)chars[i]; //找到
table[flag] = ++table[flag];
if(table[flag]==1){
sb.append((char)flag);
}
}
System.out.println(sb.toString());
}