Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How LeetCode finds the first unique character in a string

Shulou Source: shulou.com Published: 2022-06-01 13:03:23 09月26日 Update

This article is about how LeetCode finds the first unique character in a string. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. Brief introduction of the problem.

Given a string, find its first non-repeating character and return its index.

If it does not exist, return-1.

2, example

Example:

S = "leetcode" returns 0

S = "loveleetcode" returns 2

Tip: you can assume that the string contains only lowercase letters.

3, the train of thought of solving the problem

The use of keys and values on the collection LinkedHashMap

4, problem solving procedure

Import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;import java.util.Optional

Public class FirstUniquCharTest2 {public static void main (String [] args) {String s = "cc"; int firstUniqChar = firstUniqChar (s); System.out.println ("firstUniqChar =" + firstUniqChar);}

Public static int firstUniqChar (String s) {if (s = = null | | s.length () = = 0) {return-1;} char [] toCharArray = s.toCharArray (); HashMap hashMap = new LinkedHashMap (toCharArray.length); for (char c: toCharArray) {hashMap.put (c, hashMap.getOrDefault (c, 0) + 1) } Optional optionalEntry = hashMap.entrySet (). Stream (). Filter (x-> x.getValue () = = 1). FindFirst (); if (! optionalEntry.isPresent ()) {return-1;} else {Character character = optionalEntry.get (). GetKey (); return s.indexOf (character);}

}}

5. Picture version of the problem solving program.

Thank you for reading! This is the end of this article on "how to find the first unique character in a string by LeetCode". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Tags: Characters strings solution content more examples programs articles good practical pictures letters lowercase ideas articles look knowledge index questions references Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB MySQL Microsoft Shulou Technology Docker