In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
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!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.