Why subsequence(a,b).toString() is faster than substring(a,b)?
when i convert my all subsequences to substring it slows up to %7 all the time. why does it happen?
Below is my code;
private static String filterStr(String s)
{
for(int a = 0; a < s.length(); a++)
{
int c = s.charAt(a);
if(((c < 65) || ((c >90) &&(c < 97)) || (c > 122)))
{
if(c!=34 && c!=96 && c!=39)// tırnak değillerse
{
String temp = s.substring(0,a);
temp+= s.subSequence(a+1,s.length());
s = temp;
a--;
}
else
{
if(a !=0) // if not at the beginning
{
if(a == s.length()-1)
s = s.subSequence(0,s.length()-1).toString();
else
s = s.subSequence(0,s.length()-2).toString();
}
else
s = s.subSequence(1,s.length()).toString();
}
}
if(c >= 65 && c <= 90) // convert to lower case first character.
{
String temp = s.substring(1,s.length());
c+=32;
s = (char)c + temp;
}
}
return s;
}
CharSequence subSequence(int beginIndex, int endIndex) {
return this.substring(beginIndex, endIndex);
}
this is the implementation of subSequence method, It can not be faster/slower.
Related
I hava a StringBuilder Object named ans which start with lots of '0'. I try to delete all the '0' from the start of the ans until I meet a non '0' charactar.
What confuse me is the for i loop didn't finish his job. I have to make a second for i loop to clear all the 0 in the beginning.
Here is my Code.
public class No402 {
public static void main(String[] args) {
System.out.println(new No402().removeKdigits("42767854615790820292944831840714943359894187047948450037336809401264092298894490339723170235305129677267060933619172682578764724528024649451075131679109777263591648456729485464839877320061461069243974933498371934575012528555827338953724780861662784034839154178040563249817555067081448332223588411419168442553970020118370358794959779864819714402968003470365044797881527445340976945193818119467023653961507607672480115226579679195083984107550649620824228334531543881248523270728845883011347557806714125988595750797445903460187069102923827814511796767245574859856245433535202213866357865001893279481556044431076323101967578726169437167866864433985495890782177337227185218722003203201794524473658120818757906858018522776715639010350584179192618574032568118118609428514149350137179799798509363342933168141703795277960609902578193965353966732758522319326510476003141627976495471194647651191765940623801848650779996861991716801192868381714592671157213385358454372258678286185038661251898041199455484881497973936886129286780686747702354266676649133047345268803970772136574778724059680910889846701031833468068701979269662983956502485168033946609770137842651146059273082836506077338453677150197865590089199161058651336150874965473699606051616750107442277197178936688141691056518266386172813294511346655182323777419242146803539629808395049965699535272276902817614992917612927025979571436056418178949140225831714010026397581438647144388850448143782384993050908181782121784294922444218824177798052454616802442043385673094510700252387351590505241357656396376170570838637068429512330065547472613577751410152513915714166057883408992271281823592172333654887223386232551975763603851710020471730161184180640812534293795148973065648040320936081719321657015873251252438179935213522036777508405231559635933218588146968578575964379037900738820562221783370763718270548271942160879283346733139062721676158522361533668704462398258010274851756504022170692557968534354343300976925558662656552021225536052236166733671370810493478857779656160557033130699196730596823835866942383406014324343783777539237677792451989779191005800821612057527173069156047746886314264888886920021988864698336973375949221207087151293792642382667520852406157133901720414180577613687865572943934469907502558232579505371542207400025172278481715443291693401941467763248672444891029778464850850998910451866532251760265573729603802891979681199941199058262753251051247038814898450192160069049824567851341865948819288467203875175473770134200197684457826486518709881470102852093201457965720215213058487673191409542861896211110569915555788853974841074076366685605058887536260221712351483096796829688703805892797869297796003334770994443794789460259639436865437812910241961445382357524033812312224783435809748252815436505470248482168172542366777257733653560456219150752921112615226017071525633643673264241122463875175583077761780573333101393148223764295110530230833646717923630745738812086412736671406343368298252156032118474543057099651798412740139013104123480347608236951823601336247508674889789494483794628001425344165783788429049730291326775455015785327577865377064397566794918739831414079787693198248140637113125565595305998282580721676261634498566237966614318941397734268015425568890740425312778238252662876746954156253519077411732018085846119889733839268453412968907858943693089597738545774072868871022839381446938075550039536742864199000908389925554691777850180161524332130073243881970286384249150136987633055208076388268958344328919145620288311537387853748176907053434533948744876865239789707206727054699151876690589023127693784859005126867245144990541144502571475179281742590537105515917376706167473011218582298393879651200544930737095993892411425220115292455512046640587174478149165594377091626060310391405243838577142799370503965244703765138756627518023743947119802986986532252546116477951027231307131628103042104039629499919572735529345439335549727142664736202293026484344441050630567027253471369103560266482945879441209004770164675020115476783653466174012741661723993500655369697109626010269380076073933015864761704176611703072139146747597003865521022642104228419619843927108260238084570397138708740181474347163241522446780620603392403687603888076553679045954833871460870755109132271738691459746851320926797113625441143010401758187073392500078061166186149727409676020612731477477496862648324993156390312514509978182394005049176325656482925314334308846020046440000639094498194888324242274543355772503522914560552598223947118463742841515723677871749503874006924229568354106404788800337347740726960903805684221263837486950787248911647072244868181616958029769190594368044110679179639645980860201597430267777459655372871993352465518117174671133742384885531127239604520105123727230849911680326443684000340446147937873667767227624842441390296900995179520080641610292722850119464836580325090471323736225890294980142988595694394073053215895013346101834933981247547372697246437008031025334926870805534589643288626312674442549515696840972195844322623489776395993997725883102424374473386242230020052319139538725050694563793252575203302986006568926586341522483619750551265949811840701660706687971699572637332236706033725130460780147305930796689592739802762127602300331109088320407488753453562201443009583869340530260133192585867600117793558618622877626140608235883463446585052941889282771610713456594091731994663257672424562807919185250771570978748558016087655314386429181778154999037395977801201222536602668579318195917221851258101758083465833807764504478328133760033685582322103480724065531895932039917203779203156040553746346772387443929520551627122239575483559165994485703508677722865190370481258839816840706093115274279356732858077656941579688491810646089766375954256605013212947107680641700379830628558534532701353225658907237335822869646320919937486195881402477347072922997644748078880017641720321497893274887727279247817230724007001520405446788235407924339589275318658718824019308723325037628135839936194865389246778785484224136240513164802724185350906503263939998152201969404224284851353929162842159002494160461334274924788445418313020719064697643073211899597216839617241323956298475147631936745340993794786362122100021070985418754276295234662670333162104340353095385544657319880579379906274682249802800845859334842970692716308206359497045039047894058089399866389624780981978085896624346900360571598520216940381587071285958497155631482721452214648993874243450874956631856720123296440913509093669827146153180469767433504561046437484524515293979237377991209712765962632838588822180359961992788574139615251950913574644651207439995528858114472995911722528828790960400270676875166161939741700924096377882962772526118510149529098157733017933337496630319171190616687753486928733354625068986857196646261563989044574797981270617089057226390794666311751192327631540192548655459578506043592663616062769069836457346194068474176132510064511610117400341310411426000998578144122817400179584819131405912398612085587124626912794546013764785843274068027858995747888172680971572206968091015445337290861835783980747471461015521311208355915962202714480089884097249709377165451728632422251230084667248727648072440251993269156317610868685295846232492883010588697174635533597605834450249882921427658569868883414799635112078926523707047988262628826843234898036034699263633285219983947947102364186704490860419225940767023498819222899748637736136929299603365634669304329289193002180868079267831256753666692578016598885536576757243005565124272778934460000656133474422706312579704797332965888987321865639934115540341358438065159979966516649509059972742742859883148151328808103859578112480441464277834533174833896376621814776042440697291859846516369392086372254665861285937409320474020680208941413993134675771984152737919309617874095184511004441704637414657377204495521150940370391369816136133983987959653102357045282415379947968251076420098012505820501069271733453309150705588274173445852803861126110689326352001921046066346433959229953549279092972503658190837209557302503876248001129441633640343374507764567392795980560783306587466656895994346821030188171996741604459649768510697714192580042040101750692371398942842500442445462269343139517683266487839338542443169246460653530698650325346136357734184681042975047635944793223022235246268651870018710450581435529607254366048869493833744884331399960456341161524764264081615200455615465925723132075411240169896584999493701334792763601560521725937880035580427191600072833098777060365102978298741740559073275852763938780836609797603716875112885764040607658550533844408290490010802790842002942292935369291644839617793990910895308977723653062881593207714109720695034340437197019621968080117519794848132586742911614980669439330348142456126849768719198483462298008318935405664818315956667907954514033766806239587330742325680711653716183320470951491901907421070418246355033490024779722775524553362711286647617964163847164933401979458666304006708368763218332476561345205255639459643444256743045787508311558394991701816915267581835649555296896252897237006404723594796400109216516930136483261469100739753281302804818082275735965571356243205409672153514152830169411991633125429246600926046750109377245075186063774301024268884824103787866848063266853457600668442319180654169447895010411843408292686118099805402852556814966811008369348597110442872837094072059087232837205291461239853639994518924479438927379348327739109781565914159761167665584025124425923844801188360781762018699315163461229173330894272797116474430040071501881164984840886621509629770804885731934408262630754177569630312231904935609457496213783238786007928894185681679202644961896031520772120429456532334651866707926275039616875628244135012101648429121896413946679889877828086708457516884940565793756567939396973544976573326617620245079002790968407887831523704293463842790307287785628353910524550357149296905848302331279051221613790082068853444332742995671850649946821132877723913186786300652152247618157706125750578092402909964449626211673467131785274416643250628726377006207603592185", 8222));
}
public String removeKdigits(String num, int k) {
if (num.length() == k) {
return "0";
}
Deque<Character> deq = new LinkedList<>();
int howmany2cut = k;
char[] numsChar = num.toCharArray();
int finalIndx = 0;
for (int i = 0; i < numsChar.length && k > 0; i++) {
if (deq.isEmpty()) {
deq.add(numsChar[i]);
continue;
}
if (deq.peekLast() <= numsChar[i]) {
deq.add(numsChar[i]);
continue;
}
if (deq.peekLast() > numsChar[i]) {
while (k > 0) {
if (!deq.isEmpty() && (deq.peekLast() > numsChar[i])) {
deq.pollLast();
k--;
} else {
break;
}
}
deq.add(numsChar[i]);
finalIndx = i + 1;
}
}
StringBuilder ans = new StringBuilder();
for (Character n : deq) {
ans.append(n);
}
if (deq.size() < num.length() - k) {
ans.append(num.substring(finalIndx));
}
if (ans.length() > 1) {
for (int i = 0; i < ans.length(); i++) {
if ('0' == ans.charAt(0)) {
ans.delete(0, 1);
} else {
break;
}
}
} else {
return ans.toString();
}
if (ans.length() > 1) {
for (int i = 0; i < ans.length(); i++) {
if ('0' == ans.charAt(0)) {
ans.delete(0, 1);
} else {
break;
}
}
}
if (ans.length() == 0) {
return num.length() - howmany2cut > 0 ? num.substring(0, num.length() - howmany2cut) : "0";
}
if (ans.length() > num.length() - howmany2cut) {
return ans.substring(0, num.length() - howmany2cut);
}
return ans.toString();
}}
here is my debug picture
Please help me , thank you!
The reason why all 0's are not deleting after the first loop is that you are removing elements inside the loop if the first character is zero. Which causing the decrease in ans.length() so due to this the loop is not going up to the full length.
One more thing there is no need for 2 for loops you can manage it with just one loop.
How to fix?
Just store the actual length of ans before beginning the deletion and place it in the loop condition like this
public class No402 {
public static void main(String[] args) {
System.out.println(new No402().removeKdigits("42767854615790820292944831840714943359894187047948450037336809401264092298894490339723170235305129677267060933619172682578764724528024649451075131679109777263591648456729485464839877320061461069243974933498371934575012528555827338953724780861662784034839154178040563249817555067081448332223588411419168442553970020118370358794959779864819714402968003470365044797881527445340976945193818119467023653961507607672480115226579679195083984107550649620824228334531543881248523270728845883011347557806714125988595750797445903460187069102923827814511796767245574859856245433535202213866357865001893279481556044431076323101967578726169437167866864433985495890782177337227185218722003203201794524473658120818757906858018522776715639010350584179192618574032568118118609428514149350137179799798509363342933168141703795277960609902578193965353966732758522319326510476003141627976495471194647651191765940623801848650779996861991716801192868381714592671157213385358454372258678286185038661251898041199455484881497973936886129286780686747702354266676649133047345268803970772136574778724059680910889846701031833468068701979269662983956502485168033946609770137842651146059273082836506077338453677150197865590089199161058651336150874965473699606051616750107442277197178936688141691056518266386172813294511346655182323777419242146803539629808395049965699535272276902817614992917612927025979571436056418178949140225831714010026397581438647144388850448143782384993050908181782121784294922444218824177798052454616802442043385673094510700252387351590505241357656396376170570838637068429512330065547472613577751410152513915714166057883408992271281823592172333654887223386232551975763603851710020471730161184180640812534293795148973065648040320936081719321657015873251252438179935213522036777508405231559635933218588146968578575964379037900738820562221783370763718270548271942160879283346733139062721676158522361533668704462398258010274851756504022170692557968534354343300976925558662656552021225536052236166733671370810493478857779656160557033130699196730596823835866942383406014324343783777539237677792451989779191005800821612057527173069156047746886314264888886920021988864698336973375949221207087151293792642382667520852406157133901720414180577613687865572943934469907502558232579505371542207400025172278481715443291693401941467763248672444891029778464850850998910451866532251760265573729603802891979681199941199058262753251051247038814898450192160069049824567851341865948819288467203875175473770134200197684457826486518709881470102852093201457965720215213058487673191409542861896211110569915555788853974841074076366685605058887536260221712351483096796829688703805892797869297796003334770994443794789460259639436865437812910241961445382357524033812312224783435809748252815436505470248482168172542366777257733653560456219150752921112615226017071525633643673264241122463875175583077761780573333101393148223764295110530230833646717923630745738812086412736671406343368298252156032118474543057099651798412740139013104123480347608236951823601336247508674889789494483794628001425344165783788429049730291326775455015785327577865377064397566794918739831414079787693198248140637113125565595305998282580721676261634498566237966614318941397734268015425568890740425312778238252662876746954156253519077411732018085846119889733839268453412968907858943693089597738545774072868871022839381446938075550039536742864199000908389925554691777850180161524332130073243881970286384249150136987633055208076388268958344328919145620288311537387853748176907053434533948744876865239789707206727054699151876690589023127693784859005126867245144990541144502571475179281742590537105515917376706167473011218582298393879651200544930737095993892411425220115292455512046640587174478149165594377091626060310391405243838577142799370503965244703765138756627518023743947119802986986532252546116477951027231307131628103042104039629499919572735529345439335549727142664736202293026484344441050630567027253471369103560266482945879441209004770164675020115476783653466174012741661723993500655369697109626010269380076073933015864761704176611703072139146747597003865521022642104228419619843927108260238084570397138708740181474347163241522446780620603392403687603888076553679045954833871460870755109132271738691459746851320926797113625441143010401758187073392500078061166186149727409676020612731477477496862648324993156390312514509978182394005049176325656482925314334308846020046440000639094498194888324242274543355772503522914560552598223947118463742841515723677871749503874006924229568354106404788800337347740726960903805684221263837486950787248911647072244868181616958029769190594368044110679179639645980860201597430267777459655372871993352465518117174671133742384885531127239604520105123727230849911680326443684000340446147937873667767227624842441390296900995179520080641610292722850119464836580325090471323736225890294980142988595694394073053215895013346101834933981247547372697246437008031025334926870805534589643288626312674442549515696840972195844322623489776395993997725883102424374473386242230020052319139538725050694563793252575203302986006568926586341522483619750551265949811840701660706687971699572637332236706033725130460780147305930796689592739802762127602300331109088320407488753453562201443009583869340530260133192585867600117793558618622877626140608235883463446585052941889282771610713456594091731994663257672424562807919185250771570978748558016087655314386429181778154999037395977801201222536602668579318195917221851258101758083465833807764504478328133760033685582322103480724065531895932039917203779203156040553746346772387443929520551627122239575483559165994485703508677722865190370481258839816840706093115274279356732858077656941579688491810646089766375954256605013212947107680641700379830628558534532701353225658907237335822869646320919937486195881402477347072922997644748078880017641720321497893274887727279247817230724007001520405446788235407924339589275318658718824019308723325037628135839936194865389246778785484224136240513164802724185350906503263939998152201969404224284851353929162842159002494160461334274924788445418313020719064697643073211899597216839617241323956298475147631936745340993794786362122100021070985418754276295234662670333162104340353095385544657319880579379906274682249802800845859334842970692716308206359497045039047894058089399866389624780981978085896624346900360571598520216940381587071285958497155631482721452214648993874243450874956631856720123296440913509093669827146153180469767433504561046437484524515293979237377991209712765962632838588822180359961992788574139615251950913574644651207439995528858114472995911722528828790960400270676875166161939741700924096377882962772526118510149529098157733017933337496630319171190616687753486928733354625068986857196646261563989044574797981270617089057226390794666311751192327631540192548655459578506043592663616062769069836457346194068474176132510064511610117400341310411426000998578144122817400179584819131405912398612085587124626912794546013764785843274068027858995747888172680971572206968091015445337290861835783980747471461015521311208355915962202714480089884097249709377165451728632422251230084667248727648072440251993269156317610868685295846232492883010588697174635533597605834450249882921427658569868883414799635112078926523707047988262628826843234898036034699263633285219983947947102364186704490860419225940767023498819222899748637736136929299603365634669304329289193002180868079267831256753666692578016598885536576757243005565124272778934460000656133474422706312579704797332965888987321865639934115540341358438065159979966516649509059972742742859883148151328808103859578112480441464277834533174833896376621814776042440697291859846516369392086372254665861285937409320474020680208941413993134675771984152737919309617874095184511004441704637414657377204495521150940370391369816136133983987959653102357045282415379947968251076420098012505820501069271733453309150705588274173445852803861126110689326352001921046066346433959229953549279092972503658190837209557302503876248001129441633640343374507764567392795980560783306587466656895994346821030188171996741604459649768510697714192580042040101750692371398942842500442445462269343139517683266487839338542443169246460653530698650325346136357734184681042975047635944793223022235246268651870018710450581435529607254366048869493833744884331399960456341161524764264081615200455615465925723132075411240169896584999493701334792763601560521725937880035580427191600072833098777060365102978298741740559073275852763938780836609797603716875112885764040607658550533844408290490010802790842002942292935369291644839617793990910895308977723653062881593207714109720695034340437197019621968080117519794848132586742911614980669439330348142456126849768719198483462298008318935405664818315956667907954514033766806239587330742325680711653716183320470951491901907421070418246355033490024779722775524553362711286647617964163847164933401979458666304006708368763218332476561345205255639459643444256743045787508311558394991701816915267581835649555296896252897237006404723594796400109216516930136483261469100739753281302804818082275735965571356243205409672153514152830169411991633125429246600926046750109377245075186063774301024268884824103787866848063266853457600668442319180654169447895010411843408292686118099805402852556814966811008369348597110442872837094072059087232837205291461239853639994518924479438927379348327739109781565914159761167665584025124425923844801188360781762018699315163461229173330894272797116474430040071501881164984840886621509629770804885731934408262630754177569630312231904935609457496213783238786007928894185681679202644961896031520772120429456532334651866707926275039616875628244135012101648429121896413946679889877828086708457516884940565793756567939396973544976573326617620245079002790968407887831523704293463842790307287785628353910524550357149296905848302331279051221613790082068853444332742995671850649946821132877723913186786300652152247618157706125750578092402909964449626211673467131785274416643250628726377006207603592185", 8222));
}
public String removeKdigits(String num, int k) {
if (num.length() == k) {
return "0";
}
Deque<Character> deq = new LinkedList<>();
int howmany2cut = k;
char[] numsChar = num.toCharArray();
int finalIndx = 0;
for (int i = 0; i < numsChar.length && k > 0; i++) {
if (deq.isEmpty()) {
deq.add(numsChar[i]);
continue;
}
if (deq.peekLast() <= numsChar[i]) {
deq.add(numsChar[i]);
continue;
}
if (deq.peekLast() > numsChar[i]) {
while (k > 0) {
if (!deq.isEmpty() && (deq.peekLast() > numsChar[i])) {
deq.pollLast();
k--;
} else {
break;
}
}
deq.add(numsChar[i]);
finalIndx = i + 1;
}
}
StringBuilder ans = new StringBuilder();
for (Character n : deq) {
ans.append(n);
}
if (deq.size() < num.length() - k) {
ans.append(num.substring(finalIndx));
}
int tempLength = ans.length(); //Store length like this
if (ans.length() >= 1) {
for (int i = 0; i < tempLength; i++) { //pass the tempLength as termination condition like this
if ('0' == ans.charAt(0)) {
ans.delete(0, 1);
} else {
break;
}
}
}
if (ans.length() == 0) {
return num.length() - howmany2cut > 0 ? num.substring(0, num.length() - howmany2cut) : "0";
}
if (ans.length() > num.length() - howmany2cut) {
return ans.substring(0, num.length() - howmany2cut);
}
return ans.toString();
}}
I need to find the number of distinct vowels. I came up with the code below but it can't make distinction between same vowels:
public static int count_Vowels(String str) {
str = str.toLowerCase();
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u') {
count++;
}
}
return count;
}
I would start with five variables (one for each vowel) set to 0, iterate the characters in the input and set the corresponding variable to 1 if I find a match, and simply return the accumulated value of said variables. Like,
public static int count_Vowels(String str) {
int a = 0, e = 0, i = 0, o = 0, u = 0;
for (char ch : str.toLowerCase().toCharArray()) {
if (ch == 'a') {
a = 1;
} else if (ch == 'e') {
e = 1;
} else if (ch == 'i') {
i = 1;
} else if (ch == 'o') {
o = 1;
} else if (ch == 'u') {
u = 1;
}
}
return a + e + i + o + u;
}
You could use Set data structure and instead of incrementing the counter just add vowels to the set. At the end you can return just the size of the set.
The problem in your code is that you are not counting the distinct vowels, but all the vowels in the string. A Java-8 way to this:
public static int countDistinctVowels(String str) {
str = str.toLowerCase();
int count = (int) str.chars() // get IntStream of chars
.mapToObj(c -> (char) c) // cast to char
.filter(c -> "aeiou".indexOf(c) > -1) // remove all non-vowels
.distinct() // keep the distinct values
.count(); // count the values
return count;
}
Also use proper Java naming conventions: countDistinctVowels, no count_Distinct_Vowels.
there's definitely an issue here with this counting. at the very least. you should rethink this:
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u')
count++;
You could use the method contains
public static int count_Vowels(String str) {
str = str.toLowerCase();
int count = 0;
count += string.contains("a") ? 1 : 0;
count += string.contains("e") ? 1 : 0;
count += string.contains("i") ? 1 : 0;
count += string.contains("o") ? 1 : 0;
count += string.contains("u") ? 1 : 0;
return count;
}
I made explanations in the comments to the code:
public static int count_Vowels(String str) {
str = str.toLowerCase();
Set<Character> setOfUsedChars = new HashSet<>(); // Here you store used vowels
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u') { // if currently checked character is vowel...
setOfUsedChars.add(str.charAt(i)); // add this vowel to setOfUsedChars
}
}
return setOfUsedChars.size(); // size of this sets is a number of vowels present in input String
}
static void vow(String input){
String output=input.toLowerCase();
int flaga=0,flage=0,flagi=0,flago=0,flagu=0;
for(int i=0;i<input.length();i++) {
if((output.charAt(i))=='a' && flaga==0) {
System.out.print(input.charAt(i)+" ");
flaga++;
}
if(output.charAt(i)=='e' && flage==0) {
System.out.print(input.charAt(i)+" ");
flage++;
}
if(output.charAt(i)=='i' && flagi==0) {
System.out.print(input.charAt(i)+" ");
flagi++;
}
if(output.charAt(i)=='o' && flago==0) {
System.out.print(input.charAt(i)+" ");
flago++;
}
if(output.charAt(i)=='u' && flagu==0) {
System.out.print(input.charAt(i)+" ");
flagu++;
}
}
}
public static void main(String args[]) {
String sentence;
int v=0,c=0,ws=0;
Scanner sc= new Scanner(System.in);
sentence = sc.nextLine();
sc.close();
sentence.toLowerCase();
String res="";
for(int i=0;i<sentence.length();i++) {
if(sentence.charAt(i)=='a'||sentence.charAt(i)=='e'||sentence.charAt(i)=='i'||sentence.charAt(i)=='o'||sentence.charAt(i)=='u') {
if(res.indexOf(sentence.charAt(i))<0) {
res+=sentence.charAt(i);
v++;
}//System.out.println(res.indexOf(sentence.charAt(i)));
}
else if(sentence.charAt(i)==' ')
ws++;
else c++;
}
System.out.println(res);
System.out.println("no of vowels: "+v+"\n"+"no of consonants: "+c+"\n"+"no of
white spaces: "+ws);
}
You can use this Method to Find Count of Distinct vowels.
public static int count_Vowels(String str) {
char[] c = str.toLowerCase().toCharArray();
int Counter=0;
String NewString="";
for(int i=0;i<c.length;i++){
String tempString="";
tempString+=c[i];
if(!NewString.contains(tempString) && (c[i]=='a'||c[i]=='e'||c[i]=='i'||c[i]=='o'||c[i]=='u')){
Counter++;
NewString+=c[i];
}
}
return Counter;
}
Here is a solve for this problem without using objects. It's a crude but great solve for beginners who encounter this problem with limited js experience.
How to count unique vowels is a string;
function hasUniqueFourVowels(str){
let va = 0
let ve = 0
let vi = 0
let vo = 0
let vu = 0
let sum = 0
for(let i = 0; i < str.length; i++){
let char = str[i];
if(char === "i"){
vi = 1
}
if(char === "e"){
ve = 1
}
if(char === "a"){
va = 1
}
if(char === "o"){
vo = 1
}
if(char === "u"){
vu = 1
}
sum = va + vi + vo + ve + vu
if (sum >= 4){
return true
}
}
return false
}
#Test
public void numfindVoweles(){
String s="aeiouaedtesssiou";
char a[]=s.toCharArray();
HashMap<Character,Integer> hp= new HashMap<Character, Integer>();
for(char ch:a){
if(hp.containsKey(ch) && (ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u')){
hp.put(ch,hp.get(ch)+1);
}
else if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u'){
hp.put(ch,1);
}
}
System.out.println(hp);
}
I'm trying to finish this project and I can't figure how to use my existing method in my other method. I want to get rid of VOWELS, which is defined as a field the class, and I just want to use the method isVowel which returns a boolean after you type in a Char.
This is what I have:
public class StringAndIO {
private static Scanner v;
static final String VOWELS = "AaEeIiOoUuÄäÖöÜü";
public static boolean isVowel(char c) {
if (c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u'
|| c == 'U' || c == 'ä' || c == 'Ä' || c == 'ö' || c == 'Ö' || c == 'ü' || c == 'Ü') {
return true;
} else {
return false;
}
}
public static String toPigLatin(String text) {
String ret = "";
String vowelbuf = "";
for (int i = 0; i < text.length(); ++i) {
char x = text.charAt(i);
if (VOWELS.indexOf(x) != -1) {
vowelbuf += x;
} else {
if (vowelbuf.length() > 0) {
ret += vowelbuf + "b" + vowelbuf + x;
vowelbuf = "";
} else {
ret += x;
}
}
}
if (vowelbuf.length() > 0) {
ret += vowelbuf + "b" + vowelbuf;
}
return ret;
}
/**
* only there for testing purpose
*/
public static void main(String[] args) {
v = new Scanner(System.in);
System.out.println("Enter a Char!");
char c = v.next().charAt(0);
System.out.println(isVowel(c));
String s = "Meine Mutter ißt gerne Fisch";
System.out.println(s);
System.out.println(toPigLatin(s));
System.out.println();
}
}
THis is how to use your isVowel(x) method inside the other method
public static String toPigLatin(String text) {
String ret = "";
String vowelbuf = "";
for (int i = 0; i < text.length(); ++i) {
char x = text.charAt(i);
if (isVowel(x)) {
vowelbuf += x;
} else {
if (vowelbuf.length() > 0) {
ret += vowelbuf + "b" + vowelbuf + x;
vowelbuf = "";
} else {
ret += x;
}
}
}
if (vowelbuf.length() > 0) {
ret += vowelbuf + "b" + vowelbuf;
}
return ret;
}
I'm searching for ways on how to compute mathematical expressions that can compute inputs with string such as sin(90) and 10E8, until I saw these codes which I can't fully understand how these works. I want to make these as a basis because I want to improve my MDAS calculator.
I am having difficulty on understanding these codes. I'm not familiar with StringBuffer, StringTokenizer, Math.ceil, ans += mul(); , ( b.toString(), "\t" ); , but I have idea on how the trigonometric function & MDAS operation works.
Update: I've understand what is StringTokenizer but what is its relation with StringBuffer?
import java.util.*;
public class Expression {
String s, x;
double term() {
double ans = 0;
StringBuffer temp = new StringBuffer();
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
if (s.length() > 0 && s.charAt(0) == '.') {
temp.append('.');
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
if (s.length() > 0 && (s.charAt(0) == 'e' || s.charAt(0) == 'E')) {
temp.append('e');
s = s.substring(1);
temp.append(s.charAt(0));
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
ans = Double.valueOf(temp.toString()).doubleValue();
return ans;
}
double paren() {
double ans;
if (s.charAt(0) == '(') {
s = s.substring(1);
ans = add();
s = s.substring(1);
} else {
ans = term();
}
return ans;
}
double exp() {
boolean neg = false;
if (s.charAt(0) == '-') {
neg = true;
s = s.substring(1);
}
double ans = paren();
while (s.length() > 0) {
if (s.charAt(0) == '^') {
s = s.substring(1);
boolean expNeg = false;
if (s.charAt(0) == '-') {
expNeg = true;
s = s.substring(1);
}
double e = paren();
if (ans < 0) {
double x = 1;
if (Math.ceil(e) == e) {
if (expNeg)
e *= -1;
if (e == 0)
ans = 1;
else if (e > 0)
for (int i = 0; i < e; i++)
x *= ans;
else
for (int i = 0; i < -e; i++)
x /= ans;
ans = x;
} else {
ans = Math.log(-1);
}
} else if (expNeg)
ans = Math.exp(-e * Math.log(ans));
else
ans = Math.exp(e * Math.log(ans));
} else
break;
}
if (neg)
ans *= -1;
return ans;
}
double trig() {
double ans = 0;
boolean found = false;
if (s.indexOf("sin") == 0) {
s = s.substring(3);
ans = Math.sin((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("cos") == 0) {
s = s.substring(3);
ans = Math.cos((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("tan") == 0) {
s = s.substring(3);
ans = Math.tan((trig() * Math.PI) / 180);
found = true;
}
if (!found) {
ans = exp();
}
return ans;
}
double mul() {
double ans = trig();
if (s.length() > 0) {
while (s.length() > 0) {
if (s.charAt(0) == '*') {
s = s.substring(1);
ans *= trig();
} else if (s.charAt(0) == '/') {
s = s.substring(1);
ans /= trig();
} else
break;
}
}
return ans;
}
double add() {
double ans = mul();
while (s.length() > 0) {
if (s.charAt(0) == '+') {
s = s.substring(1);
ans += mul();
} else if (s.charAt(0) == '-') {
s = s.substring(1);
ans -= mul();
} else {
break;
}
}
return ans;
}
public double evaluate() {
s = x.intern();
double last = add();
return last;
}
public Expression(String s) {
StringBuffer b = new StringBuffer();
StringTokenizer t = new StringTokenizer(s, " ");
while (t.hasMoreElements())
b.append(t.nextToken());
t = new StringTokenizer(b.toString(), "\t");
b = new StringBuffer();
while (t.hasMoreElements())
b.append(t.nextToken());
x = b.toString();
}
public String toString() {
return x.intern();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter expression: ");
Expression e = new Expression(sc.nextLine());
System.out.println("\n" + e + " = " + e.evaluate() + "\n");
}
}
This program is generally reading in a string representation of a mathematical expression, and interpreting and executing that expression. As for the Java elements you're curious about:
StringBuffer is a more efficient interface to manipulating String objects.
StringTokenizer(String, String) is a class to break a string into tokens. In this constructor, the first argument is a string to break into tokens, the second argument is the delimiter used to create those tokens.
Math.ceil() returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.
StringBuffer.toString() writes out a String representing the data in the buffer
\t is a tab
+= and -= are the {add/ subtract} assignment operators, which {add / subtract} right operand to the left operand and assign the result to left operand. E.g.
int x = 0;
x += 2; // x is now 2
See javadoc for StringBuffer at http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
See javadoc for StringTokenizerat http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
I will try to comment all but the obvious lines
import java.util.*;
public class Expression {
String s, x;
double term() {
double ans = 0;
StringBuffer temp = new StringBuffer(); //Efficient than simple String
while (s.length() > 0 && Character.isDigit(s.charAt(0))) { //Check if the first character is a digit
temp.append(Integer.parseInt("" + s.charAt(0))); //If true, add to temp String
s = s.substring(1);
}
if (s.length() > 0 && s.charAt(0) == '.') {
temp.append('.');
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
if (s.length() > 0 && (s.charAt(0) == 'e' || s.charAt(0) == 'E')) {
temp.append('e');
s = s.substring(1);
temp.append(s.charAt(0));
s = s.substring(1);
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
temp.append(Integer.parseInt("" + s.charAt(0)));
s = s.substring(1);
}
}
ans = Double.valueOf(temp.toString()).doubleValue();
return ans;
}
double paren() {
double ans;
if (s.charAt(0) == '(') {
s = s.substring(1);
ans = add();
s = s.substring(1);
} else {
ans = term();
}
return ans;
}
double exp() {
boolean neg = false;
if (s.charAt(0) == '-') {
neg = true;
s = s.substring(1);
}
double ans = paren();
while (s.length() > 0) {
if (s.charAt(0) == '^') {
s = s.substring(1);
boolean expNeg = false;
if (s.charAt(0) == '-') {
expNeg = true;
s = s.substring(1);
}
double e = paren();
if (ans < 0) {
double x = 1;
if (Math.ceil(e) == e) { //Check Math.ceil documentation at http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#ceil(double)
if (expNeg)
e *= -1;
if (e == 0)
ans = 1;
else if (e > 0)
for (int i = 0; i < e; i++)
x *= ans;
else
for (int i = 0; i < -e; i++)
x /= ans;
ans = x;
} else {
ans = Math.log(-1); //http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#log(double)
}
} else if (expNeg)
ans = Math.exp(-e * Math.log(ans));
else
ans = Math.exp(e * Math.log(ans)); //http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#exp(double)
} else
break;
}
if (neg)
ans *= -1;
return ans;
}
double trig() {
double ans = 0;
boolean found = false;
if (s.indexOf("sin") == 0) {
s = s.substring(3);
ans = Math.sin((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("cos") == 0) {
s = s.substring(3);
ans = Math.cos((trig() * Math.PI) / 180);
found = true;
} else if (s.indexOf("tan") == 0) {
s = s.substring(3);
ans = Math.tan((trig() * Math.PI) / 180);
found = true;
}
if (!found) {
ans = exp();
}
return ans;
}
double mul() {
double ans = trig();
if (s.length() > 0) {
while (s.length() > 0) {
if (s.charAt(0) == '*') {
s = s.substring(1);
ans *= trig();
} else if (s.charAt(0) == '/') {
s = s.substring(1);
ans /= trig();
} else
break;
}
}
return ans;
}
double add() {
double ans = mul();
while (s.length() > 0) {
if (s.charAt(0) == '+') {
s = s.substring(1);
ans += mul();
} else if (s.charAt(0) == '-') {
s = s.substring(1);
ans -= mul();
} else {
break;
}
}
return ans;
}
public double evaluate() {
s = x.intern();
double last = add();
return last;
}
public Expression(String s) {
StringBuffer b = new StringBuffer();
StringTokenizer t = new StringTokenizer(s, " "); //Creates a iterable t object so you can iterate over each "word" separate by space
while (t.hasMoreElements())
b.append(t.nextToken());
t = new StringTokenizer(b.toString(), "\t");
b = new StringBuffer();
while (t.hasMoreElements())
b.append(t.nextToken());
x = b.toString();
}
public String toString() {
return x.intern();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter expression: ");
Expression e = new Expression(sc.nextLine());
System.out.println("\n" + e + " = " + e.evaluate() + "\n");
}
}
I have a method getRPNString(), which returns Reverse Polish Notation string. I want to split this string by spacebars to calculate it. Now I can't understand how to add spacebars in my RNP string right, because it's not working with two digits numbers.
public class Calc1 {
public static void main(String[] args) {
String in = "((5+3*(4+2)*12)+3)/(1+3)+5";
String out = getRPNString(in);
System.out.println(out);
}
private static String getRPNString(String in) {
LinkedList<Character> oplist = new LinkedList<>();
StringBuilder out = new StringBuilder();
for (int i = 0; i < in.length(); i++) {
char op = in.charAt(i);
if (op == ')') {
while (oplist.getLast() != '(') {
out.append(oplist.removeLast());
}
oplist.removeLast();
}
if (Character.isDigit(op)) {
out.append(op);
/*int j = i + 1;
for (; j < in.length(); j++) {
if (!Character.isDigit(j)) {
break;
}
i++;
}
out.append(in.substring(i, j));*/
}
if (op == '(') {
oplist.add(op);
}
if (isOperator(op)) {
if (oplist.isEmpty()) {
oplist.add(op);
} else {
int priority = getPriority(op);
if (priority > getPriority(oplist.getLast())) {
oplist.add(op);
} else {
while (!oplist.isEmpty()
&& priority <= getPriority(oplist.getLast())) {
out.append(oplist.removeLast());
}
oplist.add(op);
}
}
}
}
while (!oplist.isEmpty()) {
out.append(oplist.removeLast());
}
return out.toString();
}
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '%';
}
private static int getPriority(char op) {
switch (op) {
case '*':
case '/':
return 3;
case '+':
case '-':
return 2;
case '(':
return 1;
default:
return -1;
}
}
}
I tried to add spacebars by append(' ') in my StringBuilder variable out. But it' s not right with two digits. I think I totally do not understand how to make it.
For example if input is String in = "((5+3*(4+2)*12)+3)/(1+3)+5"; the out will be 5342+12+3+13+/5+, when I add spacebars to all calls out.append(' ')**out is **5 3 4 2 + * 1 2 * + 3 + 1 3 + / 5 +, so numbers like "12" became "1 2".
Can you help?
Just change the code that you have commented out, right after Character.isDigit(op) to:
int j = i + 1;
int oldI = i;//this is so you save the old value
for (; j < in.length(); j++) {
if (!Character.isDigit(in.charAt(j))) {
break;
}
i++;
}
out.append(in.substring(oldI, j));
out.append(' ');
I changed my method, now it works fine. I fonded my mistake when I wroted
!Character.isDigit(j) but need !Character.isDigit(in.charAt(j)).
private static String getRPNString(String in) {
LinkedList<Character> oplist = new LinkedList<>();
StringBuilder out = new StringBuilder();
for (int i = 0; i < in.length(); i++) {
char op = in.charAt(i);
if (op == ')') {
while (oplist.getLast() != '(') {
out.append(oplist.removeLast()).append(' ');
}
oplist.removeLast();
}
if (Character.isDigit(op)) {
int j = i + 1;
int oldI = i;//this is so you save the old value
for (; j < in.length(); j++) {
if (!Character.isDigit(in.charAt(j))) {
break;
}
i++;
}
out.append(in.substring(oldI, j));
out.append(' ');
}
if (op == '(') {
oplist.add(op);
}
if (isOperator(op)) {
if (oplist.isEmpty()) {
oplist.add(op);
} else {
int priority = getPriority(op);
if (priority > getPriority(oplist.getLast())) {
oplist.add(op);
} else {
while (!oplist.isEmpty()
&& priority <= getPriority(oplist.getLast())) {
out.append(oplist.removeLast()).append(' ');
}
oplist.add(op);
}
}
}
}
while (!oplist.isEmpty()) {
out.append(oplist.removeLast()).append(' ');
}
return out.toString();
}
Now it produce right expression.
Test: input: ((5+3*(4+2)*12)+3)/(1+3)+5
output : 5 3 4 2 + * 12 * + 3 + 1 3 + / 5 +