The first character position that appears only once-the sword refers to an offer

Source: Internet
Author: User

The first occurrence of a character position only once the title description

The position of the first occurrence of a character in a string (1<= string length <=10000, all composed of letters) is found. If the string is empty, return-1. Position index starting from 0

Ideas
    1. Each character is compared to the time complexity O (N2), so we create a hash table to store each character corresponding occurrences, scan the number of times, scan the second time to find the first occurrence of a character, time complexity O (n)
    2. Sacrifice space for time, hash table lookup Time is O (1)
    3. Note: The case of a character that does not meet such a condition at last
Code
PublicClass Solution {PublicIntFirstnotrepeatingchar(String str) {if (str = = NULL | | str.length () = =0) {Return-1;}int[] Table =Newint[256]; char[]strchar = Str.tochararray (); for (int i = 0; i < table.length; I + +) {Table[i] = 0;} for (int i = 0; i < strChar.length ; i++) {table[(int) strchar[i]]++;} int position = 0; while (Position < strchar.length && table[(int) strchar[position]]! = 1) {position++;} if (position = strchar.length) {return- 1;} return position;}           

The first occurrence of a character position-the sword is an offer

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.