内容简介: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; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
《Hello Ruby:儿童编程大冒险》(平装)
(芬兰)琳达·刘卡斯 / 窝牛妈 / 浙江人民美术出版社 / 2018
快来认识Ruby——一个想象力丰富,喜欢解决难题的女生。Ruby认识了一群新朋友:聪明的雪豹、友好的狐狸、忙碌的机器人等等。这本书以讲故事的方式向孩子们介绍了基础的计算思维,比如拆分问题,制定分步计划,寻找规律,打破思维定势等等;之后,通过一系列鼓励探索和创造的练习和活动,孩子们对这些关乎编程核心问题的基本概念有了进一步的理解。一起来看看 《《Hello Ruby:儿童编程大冒险》(平装)》 这本书的介绍吧!