当前位置: 首页 > 后端技术 > Java

LeetCode-387-Thefirstuniquecharacterinastring

时间:2023-04-01 18:50:55 Java

Thefirstuniquecharacterinastring题目描述:给定一个字符串,找到它的第一个唯一字符并返回它的索引。如果不存在则返回-1。例子见LeetCode官网。来源:LeetCode链接:https://leetcode-cn.com/probl...版权归LeetCode所有。商业转载请联系官方授权,非商业转载请注明出处。方案一:遍历字符串首先,如果s为null或者空字符串,直接返回-1。如果s的长度只有1,则返回索引位0。当s的长度大于1时,声明一个LinkedHashMap记录每个字符出现的次数,然后遍历s的每个字符,将每个字符和相应的出现次数进入LinkedHashMap。然后遍历LinkedHashMap,判断是否有值为1的字符只出现过一次。如果存在,则返回s中的索引位。如果遍历后不存在,则返回-1。importjava.util.LinkedHashMap;importjava.util.Map;publicclassLeetCode_387{publicstaticintfirstUniqChar(Strings){if(s==null||s.length()==0){return-1;}如果(s.length()==1){返回0;}MapcharCount=newLinkedHashMap<>();for(charc:s.toCharArray()){if(charCount.containsKey(c)){charCount.put(c,charCount.get(c)+1);}else{charCount.put(c,1);}}for(Map.EntrycharacterIntegerEntry:charCount.entrySet()){if(characterIntegerEntry.getValue()==1){返回s.indexOf(characterIntegerEntry.getKey());}}返回-1;}publicstaticvoidmain(String[]args){System.out.println(firstUniqChar("loveleetcode"));}}【每日一语】发光的不一定都是金子,沉默的不一定都是石头。