Leetcode 387. First Unique Character in a String

Source: Internet
Author: User

Problem:given a string, find the first non-repeating character in it and return it ' s index. If it doesn ' t exist, return-1.

Example:

s = "Leetcode" return 0.s = "Loveleetcode", return 2.

The first idea is to open an alphabet counter, traverse the elements in string s, and count each letter with a counter. Finally, traversing s again, looking for a count of 1 characters and then returning its index. The solution code is as follows:

1 classSolution {2  Public:3     intFirstuniqchar (strings) {4         int*alphabet =NULL;5Alphabet =New int[ -]();6          for(inti =0; I < s.length (); i++)7         {8alphabet[int(S[i]-'a')]++;9         }Ten          for(inti =0; I < s.length (); i++) One         { A             if(alphabet[int(S[i]-'a')] ==1) -             { -                 returni; the             } -         } -         return-1; -          +          -     } +};

However, if the string is very long and two traversal is expensive, you can consider a traversal, record the number and index of each letter with a hash table, with the following code:

1 classSolution {2  Public:3     intFirstuniqchar (strings) {4unordered_map<Char, pair<int,int>>m;5         intIDX =s.length ();6          for(inti =0; I < s.length (); i++)7         {8m[s[i]].first++;9M[s[i]].second =i;Ten         } One          for(Auto &p:m) A         { -             if(P.second.first = =1) -             { theIDX =min (idx, p.second.second); -             } -         } -         returnIDX = = S.length ()? -1: idx; +     } -};

Leetcode 387. First Unique Character in a String

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.