Title: The position of the first occurrence of the character in a string (1<= string length <=10000, all letters). If the string is empty, return-1.
Idea: A simple hash problem, Char takes one byte, 8 bits, representing up to 256 characters. Time complexity O (n), Spatial complexity O (1), because the hash array size is constant 256. You only need to iterate through the string once and then iterate through the hash array.
My code is as follows:
Class Solution {public: int Firstnotrepeatingchar (string str) { if (str.length () ==0) return-1; int hash[256]={0}; int i=0; while (str[i]!= ') { hash[str[i]]++; ++i; } i=0; while (str[i]!= ') { if (1==hash[str[i])) return i; ++i; } return-1; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Problem solving report-characters that appear only once for the first time