通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串过滤程序,若字符串中出现多个相同的字符,将非首次出现的字符过滤掉。
输入:
abccdeeefff输出:
abcdef思路:
利用哈希表的键(key)的唯一性即可。
import java.util.Scanner; import java.util.LinkedHashMap; public class Main { public static void main(String [] args) { Scanner sc = new Scanner(System.in); String str = sc.next(); char [] charArray = str.toCharArray();//定义一个数组,字符串转为数组 filter(charArray); } public static void filter(char [] ch) { StringBuffer sb = new StringBuffer(); // LinkedHashMap底层为数据结构链表,能够记住存入键的顺序。 LinkedHashMap<Character,Integer> hash = new LinkedHashMap<Character,Integer>(); // for-each循环 循环变量类型 循环变量名:被遍历的对象 for(char temp: ch) { //若字符在字符串中已经出现,则将字符串置于已经出现的字符位置(key的唯一性) if(hash.containsKey(temp)) hash.put(temp, 1); else //若字符在字符串中未出现,则依次放入字符串的容器中 hash.put(temp, 0); } // 遍历LinkedHashMap的键集合,并依次存放到sb中 for(char temp1:hash.keySet()) sb.append(temp1); String str1 = new String(sb); System.out.println(str1); } }