0% found this document useful (0 votes)
38 views24 pages

String Manipulation Examples

The document contains various code snippets and explanations related to string manipulation in programming. It covers topics such as checking for palindromes, finding the shortest path based on directions, and determining anagrams, among others. Additionally, it includes methods for substring extraction, character case conversion, and frequency analysis of characters in strings.

Uploaded by

Imon Nomi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views24 pages

String Manipulation Examples

The document contains various code snippets and explanations related to string manipulation in programming. It covers topics such as checking for palindromes, finding the shortest path based on directions, and determining anagrams, among others. Additionally, it includes methods for substring extraction, character case conversion, and frequency analysis of characters in strings.

Uploaded by

Imon Nomi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Slhings

ave IMMUTABUE
char(] ' b , ' ' , }

Stig sh- abte:


sh Scext (; for Single wovd
sh snextLine0; i take alltue hne.

sv-lengthco writtens the lengt wtt Spate,


(lCon Catenalien
Shing firsiName -
Nayecm
Swing lastName 'shai k";
Shing oll NName = FirstNkme t
Soplo (Follnae S

foliNane. chorAt (o) - it l Pist ue je given index chavacter in sring.

Fcheck it a shing is a Palindeme y 'Vacetav" mgdam

Ya

forC int ieo to lengta<e)


shi) =- slr (n-i-)
Code'
boolean isPalindvome (shing she
for Cint iso, iLsh lengtuc}1 +)4
iot o sl lengtal
it(sh char Arti) t shchorAt (nat-)
L3rekon false
Given a toute Contoining 4 direeions (E, w,N,s).
2- deshinaion WNEENESENNN"
path o Veath
Find the Shortest (Y)
N
ytl

{loat
4od gelshertest latu (shing fat)
Int X-0, Y=0,

for (int i=0, icpawlengkty i+1)


char div: Path chavAti)2 Shing fonelions:
llSoste Subshing
if(ir 's')1 Sobshing (beginindex, endindex): To vekn
from glven shing
*6Upperlae )’ (onves ko UpperCae.
SoLowerlase- Convers o Lower Case.
ese it (dir'w) 4int (orgave To ()’ Cormparing kuo shing in
rekwvn he inteqer
Cone Sensiive manner and
Value ieteqe
else S Concat()’ (embine any Taoo shring
Spates
6 fim ()> vemave on-neeeSsary
and Troailing edes of the given
begining
Shing
vekon MetSqvt (iaty
(tloat)
3 for a
qven Sel of sligs pint te avgot sing
'apple", ratgo. "bobano
Loitogophical Ondar
SL- Compore To (sho) l Doexn)
eqvol
z0-Ve
>0 + Ve
.fleioyagid Corgmiar
Lompare To lgrove Caye- wheve n 'a ove cqual.
Code'
Shing frols tl-'apple', "mango' "banana"
Shing lorgost- fria tel
for(int i ifroib lengta it+X
it( krga ompare

Sopo (Clargel.
What are Shrings., heap
Shig sht Ton Tor
nlern poo

Shing Shin ("tny'» vaviable

inlearing
imnutale:
why Slhings QYe

Sling shtTong' *Tony'


Tony
tor( ehar 'o' to ),26 x
Torgb
26X0 Tonye'
heap

Shing Buildev
’ As Compoved o Shing we Can Mediy ond change te Shing in

Shing Bilde
Shing Boilder ("Nayen');
Sylas Shirglilder ean Converfit in
’is not is Sing forma bof we
Me-tod "So. tosingt on Pirilie dalape
-tis Mehod only cool on cijecs not
Inteqer a-10,

a. toshig)x
Code'
Shing Boikker ( "> ((Ds)
ShingBolder
for(char ch'a; chs'e, cht
Sh append (ch
asb2csd bbccc
dd
Compression Shiaaang S
bshing sb
vekro 1
(shrcharAt
o) Sbappend
elsee
Ci))) chorAt (eUppvtaxe
She (characker. Sb-oppend
(3h-chorA}
)) Sbappend
izshrlengta)-1)4 chovAf
Ci) (Sh- 1f
148) (, leng icsh bininl ForC
append
(ch Sb
ehovAt(o)), to
(sh (aye Uppercharacler. che (har
C",ShingBuiter sh Sing
nees Boilder
(toppev
(S
si) hingoe Stale
Code
Buj is This Hai
Buj' is
-lns Sinhgoi Upper(ase
lelker
of frst tue each Cervert ator 4
word Rach
To
Code:
neosdr
shing
Lnleqer Count sh-chorAt (i+)!
4 SrcharAt tiy :
whie (ie sh. lencth()-
Count ++;

newslr +a Counttoshing ()
rekn new Slr

lowevCae Vowels Occored in a Shing entered by the


limes
6 Cout houw many im
USer:
Sring sk new Seanner (Sqshem-ib))

for(int ieo; izsh-lengthy, }*+)2


char ehe ghcharAt;
if(ch'a' | ch os'e |leb i'che|ch =*'
Count +*
7 Delermine if 2 shing ave Anagam f lach other
i uo skingh Conlain the Same thavacters bot in adterent order, they Can be
Soid lo be Anagtans
Code:
Shing shd"eart'
Slving Se- "heart'

f (shd length) slva lengtu)L


Chart1 shcharay > skrd tocbarArnayl)
chorArayt
Chart] shz Chor Away skre o
Arass Sort (shscharAyray
Aays Sert (stechorAray):
booleas exlk Anay equals (simchortay, shrechar Avay)

Sopls ("%ay are Aragyon


eltes

Þ102: Remove Outemost Pavenheses kkYk3 (o)


Valid )
in valid ’ (O, (0) bal o

it (bal>o)L
no chage /add

bal
hsubshing
)Ci, Ssobsrtij we
Cjenek while
') stj1
hello world!
144)
Ie0 d)" aOrl hello
ending berginig
J
sing Words Reverse
ain ISI 4
Mediui
Oon RUN-
ur ByDo DRY
shingt Velfo
k ekrn
It(balonte
>0)4
-balance
)
(e')t itelse
+4; balan
te
();append lesol
>0){ onte (ba t
bcharAnayt)4 C:s (chor for
balane
0, - int
Boildet shing Boilder Sing
Code
Code
Sing Venult new Shirgt>, int n chons lengta
Int nslengtat) Yeverse (chors, o, f-i)

tor( int end -o, enden, end ++)(


ifCizn) bveak, { Cchorsend] )
int i4
teverse (chors, sorl, end-)
Shing Sub Ssobshing()
"t (enull engt () o) \esoll: sob, e verse cchars, skort, 6-0%
+ resolt; eors'nw Shing (ehors)>
Veid Vevse (Char]ehors, inh 1e4, int tigtsd
while (legte ight)
Chav temp - chorstlestl
ehars le4] chars (ighBj
lo [Link] odd Nomber in Sing Chavsigh: temp'
S2

en even eVen eve


itis alveady an odd nunber
Code
forCint i-num-lengtu()-ó i20i--)L
Char Ce Nom chavAto
If (C-e-o )1.24 02 it (oorncharAt (i)%.2 -0)
rekrn nom. subshing (o1+)3
Te:- On)
reuro ";
l|: [Link] Common Refix
strs ['dog, vatocav," tor]

Code.
i (sh lengk *o)

Shing prefir Shstel:


forint i o, i refir lerghY, 44)
char Cuvent chor Prefix chorNC0Y
for (int 3-v jesh dengta, st2
t(iz shstj)- lengtkos ( str Cj1-chovi)!= Comertchor{)
y rekorn Refix Subshing (o,i)
Opimi ked'
Arays Sor (shs),
Shing Shi: shrtol
Shing &ir . sr (sh length-l
n, index = 0)
while Cidex e sh lengts)
(shr ehavAt (index) o sha, charAs Cindex))

indek+t

breaky

ten index eo 9 ; shi Subshring(o,index)


3.9c5 shmrphi Sgs

9dSome
Nen isoerphic re
Betavse n, oe isoephe isomorghit
Code'
{(slengt() ( engh)
kekorn koke
int mopstJ ew in s ,

char tors SchavAo):


har ehart ScharAt(i
4(maps (chars] ! = apt [chart])!
Yebn false
maps (chos] i+
3 mapt chart]i4
Yekrn trvc)
Euy'
13 496 Rotale Sing
S- abcde" goal- cdeab'
’abcdeabede in is qoal he is Substing of D
Code'

vekom false

Shing d s+s;
Vekorn d- Centoing (goal)y
Qoeve Piony with doAto Can we
ceo AABB ’aaa
Hauh Asc
B A
Chor
fveq
3 6664 65
122
Hab
bBABaca Aac 8-
-6s-q0 A-2
bbAa
(ov) (ov)
inqotant notfreqyeDey
is bbad res eer VeS
Same ofchors tlw order Rololve Nole- b Aabb S=
tree S
frequency Characters
By Sert 451 I5-
Medium
(sAvnytArays equal Ainog ,rekurn
(lAmoy sod Awoy
(SAvay sordAvoys
tothorAivey
t'> tyvog Chort)
Tç-0(hbg) fale tekan
Anagrarm Valid 243. Code' I4
Mop choacter,inkeners feqMhpew thhMag< zt),
to(chor Cshchor Ao1)

Mop Eney chovocle, nkego mor Meug


(a,b)’ bqel Value () - agelValwe
ho Henp-addAi| ( fveqMap .eryselt);
Shing Builder Vewlt few
uhile (Iona lleap: is Empht)
Map takyechanacley, Jnteger> enlhy - moteap-pollt;
0nt Count e enhy. qelvalve(X,
tor(int iso, ieloont, i4
tesolk append(c)
lekun Vesulk-ko Shing
I6I4. Maxì mum Nesling Depth ot -[Link] theses
f+(2*3)+(C8)/4))+1" max

14 6 4 2+1X ’ 3
’ lo X
’")+(e)+(CCs)"
Code
Int max :0, Cuw O,
for(ehor eh: [Link]@ChorAray))

urmor)
max : (urr)
clse if (chei'')
CUw-
tekrn mar,
(7: I3 Roman to
inkeger 3l6le4
Prevvake-o
Cyr Value =s
Prev valye z Prevvalue Curr valueePrevake
Curr
Tofa be s;
Prevalues Prevalw
code'
int rev Valve =o
Honb Map 2Cchavacker,înkeger > map =ew HabMapeo
hap put ('I,);
hap put (v,s0
nap- put (*, 16)
map' pu ('L, so
map" put ('e',100),
fmap' puB ('o, Sooy
tnap put('M, 1000);

chor Cuwenschor SchavAi


int urent Valve map: qet C(uwentChav)
if( tunentvalve >Prevaloede
Veult t (uwentvalue - 2* evaloe,
elsey
y Yoult + (oventvalve,
, Prewalve (uwenvalve;
rekn vesult
Medivm
8 12. ineqer to Roman
SO (00 l000
S
M
I V
83 -> XXXII] 1000

D
L
V X

Posible.
ornber
break in muliples of a, high Is -lo0 s6 -fca
I, 8S6 - (ooo 8sk-Soo = 3s6 - \00 266 s0o
2, 8S6 - loo0

Ronvan
Code:: 4o, 1o, 4, S, 4,! 4
alves] loop,900, Soo, 4oo, loo, 90, So,
In

ShingBulder(y
ShingBilder Yom an

for (ink io: ie vale eogth, is)4


while (oom 2valvesti)

Yornanppernd (ynbolsia)
Yekurn Yomon, to Slingty
8 "Shn to integer (atoi)
32 4'

B24

824 16
'3-'-3e Vesult
3 2X104e 324
Yesult \0 32
Code
int i-0, nslength;
ohile (ieo 44 SchovAt (i):

Sign -
5ekee
144)

while (in ee schorAl)2 'o' ee schorAt ) ' '


int digit ScharAf ß) -°o;
MAX .VALVE -digit)[1o)4
if (result>(ineger. MAx
teteo if ((Sign )
yrewrn Inteqer. [Link];
elset MIN-VALWE:
rekorn Integev.
Yesulk = Yesolf * lo + diqit
Te:-0t
ewrn vesolt * Signy Sc::00

25 5 longes Palindromic Subsring


S: Caba" Subshing CX
CaX
(aab x abx aba
Caba
Codev: Int mar e0, Stavt 0,end 0
boolean is Palindverme (sting , inti, int 34
while iej
ehar ch, - S charAt (j>

Yelon false

rekoro tvuey
Shing longet Rlindvome (Shing :) :
int ne slengtht
forliot ieo% ieni4)
for (int jei; jenje
is Paliodvome (s,i)rue) t

Srarti;
endi

Yewrn s'Sobsig (stort, end+)


21- (48. Me diom
Som of Beouky oj Al Subslrihg 4lslay
ehorac kers
Beauky ’ ditleveoce of Most frequent ond leat frequent
S: 'aaaç ’ 3-|:2

Code:
int n Slenqt«()%
int totalBeavly r 0) -TC-0(6)
flor(int : , izni
int freg1
int maxfreg,: 0
int minfreg- Inkeger. MAX-VALuE:
for (int j-i; jen jte
freg (S chori)-'7;
G)-o'1
max( maxfreq,feq (s-charAt
maxfreq - Math. max(maxfreq
min freq= Inteqer. MAX. VALOE
tor (in ke 0; Ke2s Kt+)
freq, fve (kI);
ninFreg- Mata-nis (in
(moxfre,-ninfrea)
total Beauky- total Beauky +
Velovo totalBeavky
Mediusn Words in a Sring
22 IS|. Revevse
8: the sky is blve
’"blue is eSky -the
Yey leurn
Yestty
*)Coonts dist- it
(
+t; Count dist-
jenj4 for(iizje
nh
Ccntyo il Aroys
Count- dist_
0; int
lengtaco sh oint
es0; int
Code
and"aba'" "ab',"ba'
abo",k-2 S.
Sobsings number
of Count 23
oord join Shing Yekvo
temp -]: lengta- (word word
length--i word
(coord wordetit
wordati; tenp Shing
Medum
4 921 Minimm Add to make Parenthe ses val1d
Pavertuenes we iant do add ("
S ) To Make

Code
Chavocter st: tew Stocke(;
Stack L
io, ws lergtozi) TC-Or)
int
for( Char eh SchorAt{),
SC-06)

Shaek-push(ch

it (staek-istrph l)(| stad peek)


spush (chy
else
St popl

rekoro st. sie A

DRY RUN
,
cie>opeo invaid.
2
oplimaited ode:

()v i-o; is-lengiht)>i)<


forl intchar h -[Link])>

open+*) SC:-000

close+4

Open--)

Vetovn (open + clase );


Medom
25 38 Coont and Soy

21

Code!
it
f (ne) vekorn";
Shing Prev - CountAndsay (h
SringBuilder Sb e new shing Boildety
int Count =
fov(int i=y izRev lerqth0;i++)
f (Prer-chavAt (i) z Prev chaxAt (i-))

elseq
(i-),
Sb append Count).append (Rrev chorAt
Count

Sb-append(Count). append (Prev- chavAt(Arev lertu)-)

26 In dex ot tue first Occowence of attern in a text


text 9tt3tg 9 4 9 f9
Raters g9 45
-\y Yekvr
Count vehn
(sbrindexat
-) () it
+t; Count
append
(a Sb
eount Yekur
indexot(-)1 lerng (sb- If
Count
tt
()% append Sb
b:leng(1) lengta).e (sb while
Buildery Shing new Bulder
=sb Sting
Code
'cdabedab' ,be abcd Qs
Match Sring Repeated 686- 27
Medium
Tekrn
i;
break
Ciaj) chorAt (texl If
charAHG) Pattern.
4a)4ts-Ps, ic0, (int for
lengtut Patlern Psint
text-lengtu( ts: int
Code'
28 28 Find the index of tue First Oeeuwence in a Sing
haysack "Sadbutsad', needle "Sad'
’0 becavse Sad' Oceuved in index o"
Code
i (needle. is fmply(0)

ind index baystack itdexot (nedle);


3 Vekorn index
(Havd)
29: 214. Shortest Palindvome
3 abed?
S- aaCeCaaa
aaaleCaaa" ’ deba bed

code'
Sting
for(int i=0, izs ength| , is)e
it (s stortsitu (tev: Subehing i) ) 4
tekurr rev subshing(o. i) +s;
Yekwro "

3o. (392 Lengest Hapry Prefix len 14

S abab ab G 2 3 4
Code
ink (1 Table (Sling at)
int n- Pat lengtut

while (ien)
i{ (Pal chavAt(i) * PatchorAt (len)){
len t
Pitij leny

elset
Nlen Pillen-1];
esee
14

relwvo p

int Pio PiTable (s); o


th-t
int maxlen Pi[s:leng
Shing Boilder U;
SlringBuilder Yesult new

relorn Vestostwing(>

You might also like