Lintcode Easy title: Unique characters to determine if a string has no duplicate characters

Source: Internet
Author: User
Tags lintcode

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

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.