問題描述:
輸入一個字符串,求出該字符串包含的字符集合。
輸入描述:
每組數據輸入一個字符串,字符串最大長度爲100,且僅包含字母,不可能爲空串,區別大小寫。
輸出描述:
每組數據一行,按串聯前綴的字符順序,輸出字符集,即重複出現並靠後的字母不輸出。
輸入
abcqweracb
輸出
abcqwer
分析:
利用map集合來將輸入的數字存下來,作爲最後的結果。有一個前提:那就是不能存儲重複的元素,題目中也明確指出,重複的元素不輸出。
做法:
1.首先遍歷輸入字符串中的每個字符,如果map中沒有包含該字符,那麼就添加到map中(key爲index,value爲添加的字符)。用index來記錄存入數據的順序,防止輸出時順序被打亂。
2.當將所有的字符都遍歷完後,再次遍歷map集合中的元素,輸出map中的value值。
import java.util.*;
public class StringTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String str = in.nextLine();
Map<Integer,Character> map = new HashMap<>();
int index = 0;
for(int i = 0;i<str.length();i++){
if(!map.containsValue(str.charAt(i))){
map.put(index,str.charAt(i));
index ++;
}
}
for (int i = 0; i < map.size(); i++) {
System.out.print(map.get(i));
}
System.out.println();
}
in.close();
}
}