题解 | #找出字符串中第一个只出现一次的字符#
找出字符串中第一个只出现一次的字符
https://www.nowcoder.com/practice/e896d0f82f1246a3aa7b232ce38029d4
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 String str = in.nextLine(); List<Character> list = new ArrayList<>(); for(int i = 0;i < str.length();i++){ //临时字符串 //把字符替换成空字符,计算字符串的长度差 String temp = str.replaceAll(String.valueOf(str.charAt(i)),""); //System.out.println("******string:" + temp + " ***i:" + i); int count = str.length() - temp.length(); //System.out.println("******count:" + count + "***" + str.length() + "***" + temp.length()); //表示第一个字母只出现一次,直接返回 if(count == 1){ System.out.println(str.charAt(i)); return; } } System.out.println(-1); } }