We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importjava.io.*;importjava.util.*;importjava.util.regex.Pattern;importjava.util.regex.Matcher;publicclassSolution{publicstaticvoidmain(String[]args){Scannerscanner=newScanner(System.in);// Pattern pattern = Pattern.compile("^(tac)(tac(tic)?)*$"); //WORKSPatternpattern=Pattern.compile("^(\\2tic|(tac))+$");//same as go!go!amigo exampleMatchermatcher=pattern.matcher(scanner.nextLine());System.out.println(matcher.find());}}/*----------Option 1: "^(tac)(tac(tic)?)*$"--------String should not start with tic. So it should start with tac.tac can follow either tac or tic.tic cannot follow another tic.First tic should be after at least two tacs.So the regex becomes: Start with tac + Followed by either tac / tactic as many times.So tac(tac/tactic)(tac/tactic)(tac/tactic)...----------Option 2: "^(\\2tic|(tac))+$"--------Break (\\2tic|(tac)) as : group_2 = tac group_1 = (group_2 and tic) OR (group_2)So regex = (\\2tic|(tac))+ = (group_1)+ = 1 or more repetition of group_1 (Note: group_1 has two alternatives) First it will try to match group_2 and tic but still we didn't capture group_2 so we don't get it at first place. So it will match group_2 == tac This will make group_1 == (tactic|tac)Then because of + we can match any alternatives from (tactic|tac) more than 1 times.This combination is same as the Option 1*/
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Forward References
You are viewing a single comment's thread. Return to all comments →
Java 15: