repl.it
@shachopin/

First Position Unique Character

Java

No description

fork
loading
Files
  • Main.java
  • jdt.ls-java-project
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Main {
  public static void main(String[] args) {
    System.out.println("Hello world!");
  }
}
先将所有字符扫一遍,保存出现过的字符,然后再扫一遍,遇到第一个出现一次的字符就是答案。

MySolution on lintcode 646 First Position Unique Character

public class Solution {
    /**
     * @param s: a string
     * @return: it's index
     */
    public int firstUniqChar(String s) {
        // write your code here
        int[] countS = new int[256];
        char[] chars = s.toCharArray();
        
        for (char ch : chars) {
            countS[ch]++;
        }
        
        for (int i = 0; i < chars.length; i++) {
            char currentChar = chars[i];
            if (countS[currentChar] == 1) {
                return i;
            }
        }
        
        return -1;
    }
}