The first occurrence of a character Java implementation __ algorithm

Source: Internet
Author: User
Topic description

Finds the first occurrence of a character in a string (1<= string length <=10000, all composed of uppercase and lowercase letters), and returns its position

Analysis: Because the topic is related to the number of characters, we can not count the number of occurrences of each character in the string, to this end, we need a data container to store the number of times each character appears in the string, this data can be based on the number of characters to find the occurrence, In other words, the function of the container is to map a character to a number. In a commonly used data container, the hash table is formally used for this purpose.

Import Java.util.Scanner;

public class Main {public
	static void Main (string[] args) {
		Scanner input = new Scanner (system.in);
		String Str=input.next ();
		int Index=firstnotrepeatingchar (str);
		SYSTEM.OUT.PRINTLN (index);
	}

	 public static int Firstnotrepeatingchar (String str) {
		 int[] hash=new int[256];
		 int len=str.length ();
		 for (int i=0;i<len;i++) {
			 char temp=str.charat (i);
			 hash[temp]++;
		 }
		 int i;
		 for (i=0;i<len;i++) {
			 char temp=str.charat (i);
			 if (hash[temp]==1) return
				 i;
		 }
	        Return-1
	    }

}

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.