• + 0 comments

    Java 15:

    import java.io.*;
    import java.util.*;
    import java.util.regex.Pattern;
    import java.util.regex.Matcher;
    public class Solution {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            // Pattern pattern = Pattern.compile("^(tac)(tac(tic)?)*$");    //WORKS
            Pattern pattern = Pattern.compile("^(\\2tic|(tac))+$"); //same as go!go!amigo example
            Matcher matcher = 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
    */