题目描述
一个字符串全部由字母组成,如果存在只出现一次的字符,则返回第一个字符的位置,如果不存在怎返回-1.
思路:
因为要寻找第一个只出现一次的字符,所以必须全部遍历,用某个数据结构保存每个位置字符的信息。第二次遍历要在该数据结构中查找值,并且是常熟时间,那么可以采用HashSet。
1. 先用一个HashSet保存字符串中所有的字符+去重;
2. 用第二个HashSet保存出现过多次的字符;
代码如下:
import java.util.HashSet;
import java.util.Scanner;
/**
* @author Mengjun Li
* @create 2017/10/14
* @since 1.0.0
*/
public class Main1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String str = sc.nextLine();
System.out.println(onlyOnce(str));
}
}
public static int onlyOnce(String str) {
HashSet<Character> set1 = new HashSet<>();//用于存储所有字符+去重
HashSet<Character> set2 = new HashSet<>();//用于存储出现过2次以上的字符
int len = str.length(), i = 0;
while (i < len) {
if (!set1.add(str.charAt(i)))
set2.add(str.charAt(i));
i++;
}
i = 0;
while (i < len) {
if (!set2.contains(str.charAt(i)))
return i;
i++;
}
return -1;
}
}
输入输出如下:
strstri
6
strstr
-1
时间复杂度O(n),空间复杂度O(n)