Topic:
Determine if a string has no repeating characters
Implements an algorithm that determines whether characters in a string are unique occurrences
Sample Example
Give "ABC", Return True
Give "AaB", return False
Challenge
If you don't use extra storage space, how does your algorithm change?
Solving:
Defining a collection is the simplest.
Java Program:
Public classSolution {/** * @paramstr:a String *@return: A Boolean*/ Public BooleanIsUnique (String str) {//Write your code hereTreeSet set =NewTreeSet (); for(intI=0;i<str.length (); i++) if(Set.add (Str.charat (i)) = =false) return false; return true; }}
View Code
Total time: 2209 ms
Java Program:
Public classSolution {/** * @paramstr:a String *@return: A Boolean*/ Public BooleanIsUnique (String str) {//Write your code here for(intI=0;i<str.length (); i++){ for(intJ=i+1;j<str.length (); j + +){ if(Str.charat (i) = =Str.charat (j))return false; } } return true; }}
View Code
Total time: 1095 ms
This should not count as extra storage space, Time complexity O (n2)
Python program:
Using dictionaries
classSolution:#@param s:a String #@return: A Boolean defIsUnique (self, str):#Write your code hereD = {} forSinchStr:ifS not inchD:d[s]= 1Else: returnFalsereturnTrue
View Code
Total time: 255 ms
Lintcode Easy title: Unique characters to determine if a string has no duplicate characters