You are on page 1of 8

9/20/2016

5WaystoDetermineifStringhasallUniqueCharacters:JavaCodewithExample|JavaHungry

JAVAHUNGRY

Searchthisblog...

Search

Javadeveloperstutorialsandcoding.
HOME
SCJP

STRING

COLLECTIONS

THREADS

INTERVIEW

BESTJAVABOOKS

INTERVIEWTIPS

JAVACODINGPROGRAM

DATASTRUCTURES

MOREJAVATOPICS

5WaysToDetermine
IfStringHasAll
UniqueCharacters:
JavaCodeWith
Example

WHATSHOT
DifferencebetweenArraylistandVector:
CoreJavaInterviewCollectionQuestion

BestBooksforLearningJava

AmazonInterviewQuestion:FirstNon

Inthetechnicalinterviews,youmay
comeacrossthisquestionmanytimes
,determinewhetherastringhasall
uniquecharactersornot.Before
movingtothesolution,hereinthis
questionwehavetakenone
assumptionthatisallthecharacters
inthestringareASCIIcharacters.
Forthosewhoarenotfamiliarwith
ASCIIcharacters.

repeatedcharacterinString

Counttotalnumberoftimeseachalphabet
appearsinthestringjavaprogramcodewith
example

Java8newfeatures:Lambdaexpressions,
optionalclass,Defendermethodswith
examples

ASCIIabbreviationisknownas
AmericanStandardCodefor
InformationInterchange.
Insimplewordsitisjustthenumber
representationofcharacters.
So,Firstunderstandthequestionby
writingexamples:

Javahungry
LikePage

Input:Aliveisawesome
Output:false

2.7Klikes

SubscribeforOurNewsletter

Input:Livepresentmoment
Output:false
Input:Aliveswum

POPULARPOSTS

http://javahungry.blogspot.com/2014/11/stringhasalluniquecharactersjavaexample.html

1/8

9/20/2016

5WaystoDetermineifStringhasallUniqueCharacters:JavaCodewithExample|JavaHungry

Output:true

JavaInterviewQuestions

Top50JavaCollectionsInterviewQuestions

PseudoCodeforMethod1:
1.CreateaHashSetobject.
2.Scanthewholestring,andadd
eachcharacteronebyonetothe
HashSetobject
3.Iftheaddobjectreturnstruethen
continue
elsereturnfalse

andAnswers

WhatMakesYouStandoutfromtheCrowd

Threads,LifecycleExplainedwithExample

CountnumberofwordsintheStringwith
Example:JavaProgramCode

Method1
importjava.util.ArrayList
importjava.util.Collections
importjava.util.HashSet
publicclassuniquechar{

publicstaticvoidmain(Stringargs[])
{
booleanresult=false
Stringinputstring="Alvei@wsom"
System.out.println(inputstring)
HashSet<Character>uniquecharset=
for(inti=0i<inputstring.length()i++)
{
result=uniquecharset.add(inputstring.
if(result==false)
break
}
System.out.println(result)}
}

PseudoCodeforMethod2:
1.Scantheinputstring,takeeach
characteronebyoneandsetcount
flagto0.
2.Foreachcharacterinthe
http://javahungry.blogspot.com/2014/11/stringhasalluniquecharactersjavaexample.html

2/8

9/20/2016

5WaystoDetermineifStringhasallUniqueCharacters:JavaCodewithExample|JavaHungry

inputstring,Rescantheinputstring
andcomparethecharacterwitheach
characterappearintheinputstring
3.Ifequalthenincreasethecountby
1
elsecontinuetheloop
4.Ifcountflagvalueisgreaterthan1
thenreturnfalse
elsereturntrue

Method2
importjava.util.ArrayList
importjava.util.Collections
importjava.util.HashSet
publicclassUniqueChar2{

publicstaticvoidmain(Stringargs[])
{
booleanresult=false
Stringinputstring="Aliveisawesome"
System.out.println("Stringmethod2answer"
}

publicstaticbooleanmethod2(Stringinput)
{
for(inti=0i<input.length()i++)
{
charcharcterofinputstring=input.
intcount=0
for(intj=ij<input.length()j++)
{
if(charcterofinputstring==input.
count++
}
if(count>1)
returnfalse
}
returntrue
}
}

http://javahungry.blogspot.com/2014/11/stringhasalluniquecharactersjavaexample.html

3/8

9/20/2016

5WaystoDetermineifStringhasallUniqueCharacters:JavaCodewithExample|JavaHungry

PseudoCodeforMethod3:
1.indexOf()returnstheindexoffirst
occurenceofthecharacterorelse
return1.So,herewearecreatingan
arraylistobject.
2.Scantheinputstringandaddthe
indexofeachcharactertothearraylist
object.
3.Sortthearraylistobject.

4.
Compare
the
valuesof
each
adjacent
positions
of
arraylistobject
ifequalthenreturnfalse
elsecontinuescanningthe
arraylist
5.returntrue

Method3
importjava.util.ArrayList
importjava.util.Collections
importjava.util.HashSet
publicclassUniqueChar3{

publicstaticvoidmain(Stringargs[])
{
booleanresult=false
Stringinputstring="Aliveisawesome"
System.out.println("Stringmethod3answer"
}
publicstaticbooleanmethod3(Stringinput)
{
http://javahungry.blogspot.com/2014/11/stringhasalluniquecharactersjavaexample.html

4/8

9/20/2016

5WaystoDetermineifStringhasallUniqueCharacters:JavaCodewithExample|JavaHungry

ArrayListar=newArrayList()
for(inti=0i<input.length()i++)
{
intj=input.indexOf(input.charAt
ar.add(j)
}
Collections.sort(ar)
for(inti=0i<(ar.size()1)i++)
{
if(ar.get(i)==ar.get(i+1))
returnfalse
}
returntrue
}
}

PseudoCodeforMethod4:
1.Forthismethodweneedtoknow
abouttwoinbuiltfunctionsinjava,
indexOf()whichreturnstheindexof
firstoccurenceofthecharacterinthe
string,whilesecondfunction
lastIndexOf()returnstheindexoflast
occurenceofthecharacterinthe
givenstring.
2.First,weconvertthegiven
inputstringintocharacterarrayby
usingtoCharArray()function.
3.CalculatetheindexOf()and
lastIndexOf()foreachcharacterinthe
giveninputstring
4.Ifbothareequalthencontinueand
makeresult=true
elsesetflagresult=false
5.Returnresult

Method4
importjava.util.ArrayList
importjava.util.Collections
importjava.util.HashSet
publicclassUniqueChar4{

http://javahungry.blogspot.com/2014/11/stringhasalluniquecharactersjavaexample.html

5/8

9/20/2016

5WaystoDetermineifStringhasallUniqueCharacters:JavaCodewithExample|JavaHungry

publicstaticvoidmain(Stringargs[])
{
booleanresult=false
Stringinputstring="Aliveisawesome"
System.out.println("Stringmethod4answer"
}

publicstaticbooleanmethod4(Stringinput)
{
booleanresult=false
for(charch:input.toCharArray())
{
if(input.indexOf(ch)==input.lastIndexOf
result=true
else
{
result=false
break
}
}
returnresult
}
}

Method5
Mostmemoryefficientanswer
Pleasementioninthecommentswhat
isthetimecomplexityofeachofthe
abovemethodandwhy?
Alsowriteincommentsifyouhave
anyothermethodtofindallthe
uniquecharactersinstring.

Like 1

Tweet

Share

1
StumbleUpon

http://javahungry.blogspot.com/2014/11/stringhasalluniquecharactersjavaexample.html

6/8

9/20/2016

5WaystoDetermineifStringhasallUniqueCharacters:JavaCodewithExample|JavaHungry

AboutTheAuthor
Subham Mittal has worked in
Oraclefor3years.
Formorejavaarticles,Clickhere
toSubscribeJavaHungry

Youmightalsolike
INTERVIEWTIPS
CoreJavaCoding/ProgrammingQuestions
andAnswers:TechnicalInterviewinJava
HowtoConvertMathNumbertoEquivalent
ReadableWordinJava:CodewithExample
Langton'sAnt:JavaProgramCodeexplain
Recommendedby

Comments
Recommend

Community

Share

Login

SortbyBest

Jointhediscussion

EdsonAlvesPereiraayearago

ibelievebitwiseoperationsinrawchar
arrayisfaster.
1

Reply Share

sreenath2yearsago

Nicearticle,
Removethislinefromsolution1
chartemp=inputstring.charAt(i)
Itsnotrequired.
1

Reply Share
subhammittal Mod >
sreenath 2yearsago

Thankssreenath!!Updatedthe
post.Keepvisitingjavahungry:)

Reply Share
http://javahungry.blogspot.com/2014/11/stringhasalluniquecharactersjavaexample.html

7/8

9/20/2016

5WaystoDetermineifStringhasallUniqueCharacters:JavaCodewithExample|JavaHungry

sudheeramonthago

importjava.util.*
classx1
{
publicstaticvoidmain(String[]args)
{
inti=0
Strings2="Aliveswum"
TreeSets=newTreeSet()
while(i<s2.length()){=""
s.add(s2.charat(i))=""i++=""}=""
if(s.size()="=(s2.length()))"
system.out.print("true")=""else=""
system.out.print("false")=""}=""}="">

Reply Share
RahulLokurte3monthsago

publicclassUniqueString{
booleanisUniqueString(Stringstr){
if(str.length()>128)
returnfalse
boolean[]char_set=newboolean[128]
for(inti=0i<str.length()i++){
intval=str.charAt(i)
if(char_set[val]){
returnfalse
}
char_set[val]=true
}
returntrue
}
publicstaticvoidmain(String[]args){
UniqueStringunique=new
UniqueString()
booleanuniqueness=
unique.isUniqueString("Helmgmnfjfo")
System.out.println(uniqueness)
}
}

Reply Share
NehaSingla

ReturntoTop

JavaHungryCopyright2016AllRightsReserved.Designedbystudiopress

http://javahungry.blogspot.com/2014/11/stringhasalluniquecharactersjavaexample.html

8/8

You might also like