LeetCode 387. First Unique Character in a String

来源:互联网 发布:c语言可以找什么工作 编辑:程序博客网 时间:2024/06/08 00:06

387. First Unique Character in a String

Description

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

Examples:s = "leetcode"return 0.s = "loveleetcode",return 2.

Solution

  • 题意即返回一个字符数组中第一个不重复(就是说在整个字符串中,该字母只出现一次)字母的下标,不存在则返回-1.
  • 我的做法是先将该字符串存入一个哈希表中(由于只有26个字符,可以直接用线性哈希表)(同时记录字符数),然后按照下标从小到大查询,如果有只出现一次的字符,那么返回该字符对应的下标,否则结尾返回-1,代码如下:
int firstUniqChar(char* s) {    int hash_alpha[26];    memset(hash_alpha,0,sizeof(hash_alpha));    int len = strlen(s);    for (int i = 0;i < len;i++) {        hash_alpha[s[i] - 'a']++;    }    for (int i = 0;i < len;i++) {        if (hash_alpha[s[i] - 'a'] == 1)            return i;    }    return -1;}
阅读全文
0 0
原创粉丝点击