387. First Unique Character in a String

栏目: Java · 发布时间: 6年前

内容简介:Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.Examples:难度: easy

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.

难度: easy

题目:给定字符串,找出第一个不重复的字符,并返回其下标。如果不存在则返回-1.

思路:数组分别记录下标与出现次数。

Runtime: 10 ms, faster than 93.94% of Java online submissions for First Unique Character in a String.

Memory Usage: 40 MB, less than 14.74% of Java online submissions for First Unique Character in a String.

class Solution {
    public int firstUniqChar(String s) {
        int[] count = new int[26];
        int[] index = new int[26];
        int result = s.length();
        for (int i = 0; i < result; i++) {
            char c = s.charAt(i);
            count[c - 'a']++;
            index[c - 'a'] = i + 1;
        }
        
        for (int i = 0; i < 26; i++) {
            if (1 == count[i]) {
                result = Math.min(result, index[i] - 1);
            }
        }
        
        return result >= s.length() ? -1 : result;
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

游戏编程模式

游戏编程模式

Robert Nystrom / GPP翻组 / 人民邮电出版社 / 2016-9-1 / 61.4

游戏开发一直是热门的领域,掌握良好的游戏编程模式是开发人员的应备技能。本书细致地讲解了游戏开发需要用到的各种编程模式,并提供了丰富的示例。 全书共分20章,通过三大部分内容全面介绍了与游戏编程模式相关的各类知识点。首部分介绍了基础知识和框架;第二部分深入探索设计模式,并介绍了模式与游戏开发之间的关联;第三部分介绍了13种有效的游戏设计模式。 本书提供了丰富的代码示例,通过理论和代码示例......一起来看看 《游戏编程模式》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器