File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ private static int solution(String input) {
2
+ //只出现一次的字符的编号,以leetcode为例
3
+ int index = 1;
4
+ //26个英文字母,初始化一个长度为26的整形数组,第一个位置表示a的值,
5
+ //第二个位置表示b的值,依此类推,数组中有三类值,-1,0,大于等于1的整数
6
+ //-1表示字母出现两次或两次以上,0表示从未出现,大于等于1的整数表示只出现一次
7
+ //的字母的序号
8
+ int[] array = new int[26];
9
+ for (int i = 0; i < input.length(); i++) {
10
+ //将字符串中的字符转化为数组中的下标,例如a的asc码值为97,对应数组中的下标为0
11
+ int charIndex = (int)input.charAt(i) - 97;
12
+ if (array[charIndex] == 0) {
13
+ //第一次出现,序号为index
14
+ array[charIndex] = index;
15
+ //index自增,记录下一个第一次出现的字符
16
+ index++;
17
+ } else {
18
+ //字符已经出现过,即一个字符出现两次或者两次以上
19
+ array[charIndex] = -1;
20
+ }
21
+ }
22
+ char result = '#';
23
+ //遍历array数组,找到最小的index,index>=1
24
+ //记录最小的index
25
+ int resultIndex = Integer.MAX_VALUE;
26
+ for (int j = 0; j < array.length; j++) {
27
+ if (array[j] > 0 && array[j] < resultIndex) {
28
+ resultIndex = array[j];
29
+ result = (char)(j + 97);
30
+ }
31
+ }
32
+ if (result == '#') {
33
+ return -1;
34
+ }
35
+ //找到result在字符串中第一次出现的位置
36
+ for (int k = 0; k < input.length(); k++) {
37
+ if (result == input.charAt(k)) {
38
+ return k;
39
+ }
40
+ }
41
+ return -1;
42
+ }
You can’t perform that action at this time.
0 commit comments