Problem
Given a string, find the first non-repeating character in it and return it"s index. If it doesn"t exist, return -1.
ExampleGiven s = "lintcode", return 0.
Given s = "lovelintcode", return 2.
TagsAmazon Microsoft Bloomberg
Solutionclass Solution { public int firstUniqChar(String s) { int[] dict = new int[26]; for (int i = 0; i < s.length(); i++) { dict[s.charAt(i)-"a"]++; } for (int i = 0; i < s.length(); i++) { if (dict[s.charAt(i)-"a"] == 1) return i; } return -1; } }
public class Solution { public int firstUniqChar(String s) { //store string in an array char[] str = s.toCharArray(); //use HashMap to check each character"s frequency Mapmap = new HashMap<>(); for (int i = 0; i < str.length; i++) { char ch = str[i]; //reset duplicate chars to "#" if (map.containsKey(ch)) { str[map.get(ch)] = "#"; str[i] = "#"; } else { map.put(ch, i); } } int index = str.length; for (int i = 0; i < str.length; i++) { //find the first character that is not "#" and return its index if (str[i] != "#") { return i; } } //if no unique character, return -1 return -1; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/68097.html
摘要:和完全一样的做法,只要在初始化首行和首列遇到时置零且即可。对了,数组其它元素遇到也要置零喏,不过就不要啦。 Problem Follow up for Unique Paths: Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle...
Problem Given a string source and a string target, find the minimum window in source which will contain all the characters in target. Notice If there is no such window in source that covers all charac...
摘要:双指针法的解法。然后用和夹逼找到使三数和为零的三数数列,放入结果数组。对于这三个数,如果循环的下一个数值和当前数值相等,就跳过以避免中有相同的解。 Problem Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplet...
摘要:简单的动规题目,建立数组。坐标为矩阵的坐标,值为从左上角到这一格的走法总数。赋初值,最上一行和最左列的所有格子的走法都只有一种,其余格子的走法等于其左边格子走法与上方格子走法之和。最后,返回即可。 Problem A robot is located at the top-left corner of a m x n grid (marked Start in the diagram ...
摘要:建立一个长度为的数组,统计所有个字符在出现的次数,然后减去这些字符在中出现的次数。否则,循环结束,说明所有字符在和中出现的次数一致,返回。 Program Write a method anagram(s,t) to decide if two strings are anagrams or not. Example Given s=abcd, t=dcab, return true....
阅读 1255·2021-10-08 10:05
阅读 4068·2021-09-22 15:54
阅读 3084·2021-08-27 16:18
阅读 3083·2019-08-30 15:55
阅读 1405·2019-08-29 12:54
阅读 2727·2019-08-26 11:42
阅读 526·2019-08-26 11:39
阅读 2081·2019-08-26 10:11