lintcode(646)First Position Unique Character

来源:互联网 发布:淘宝零食店排行榜 编辑:程序博客网 时间:2024/06/08 05:56

描述:

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

样例:

Given s = "lintcode", return 0.

Given s = "lovelintcode", return 2.

思路:

逐个字符遍历,查看以 i 为分割点前后两个字符串是否包含重复字符

或者建立hashmap,存储字符信息

public class Solution {    /**     * @param s a string     * @return it's index     */    public int firstUniqChar(String s) {        // Write your code here        if(s == null || s.length() == 0){            return -1;        }        for(int i = 0;i<s.length() - 1;i++){            char p = s.charAt(i);            if(s.indexOf(p , i + 1) < 0 && s.indexOf(p) == i){                return i;            }        }        if(s.indexOf(s.charAt(s.length() - 1)) == s.length() - 1){            return s.length() - 1;        }        return -1;    }}


0 0
原创粉丝点击