Saturday 13 December 2014

Three letter pattern A string str has been provided as input. The objective is to find three character patterns in str starting with ‘t’ and ending with the char ‘p’. For all such patterns, the middle character is removed. tpPattern(“tiptop”) = “tptp” tpPattern(“tip.tip..tip”) = “tp.tp..tp” tpPattern(“tpttipptptaptptopp”) = “tpttpptptptptpp”

package Module2.module2a.module2c;
import static java.lang.Character.isLowerCase;
/**
 *
 * @author SUNIL
 */


public class LetterPattern {

 static String testcase1 = "Tip.TiP..tip";

 public static void main(String args[]){
 LetterPattern testInstance= new LetterPattern();
 String result = testInstance.changeLetters(testcase1);
 System.out.println(result);
 }

  public String changeLetters(String str){
    String newString="";
    String holdT="";
    String holdP="";
    int i=0;
    //if the case is (tip.....)
    if(str.charAt(0)=='t'&&str.charAt(2)=='p'){
        newString="tp";
        System.out.println("newString is::"+newString);
        i=3;//i will check from (.)
    }
    //else for any case, first two letter extracted and given to newString and i=2,coz (Hellotop)---this case after H and e the i will check from l
    else{
       char tempfirst=' ';
        char tempSecond=' ';
        tempfirst=str.charAt(0);
       
        tempSecond=str.charAt(1);
        newString=str.valueOf(tempfirst)+str.valueOf(tempSecond);
        i=2;
    }
    //if there is t,p present in string then move on else go to line 88.
 if(str.indexOf("t",2)>=1&&str.indexOf("p",2)>=1){    //2nd
    for(i=i;i<str.length();i++){
       
      
       
     if(str.substring(i).length()>2){//this is for tiptoptoooooAB ,in this case AB print and tiptip,in this case after reaching to last tip ,means after t there is no check ,coz if it check then next i and p us going to add in newString.
        
         holdT=str.valueOf(str.charAt(i));
         holdP=str.valueOf(str.charAt(i+2));
       
         if(holdT.equals("t")&&holdP.equals("p")){//actual checking of tip
           
             newString=newString+holdT+holdP;
                    if(i+2>0)//Indexoutof bound exception
                        i=i+2;
                    else
                        break;
            }
            else//if tip case not found
            newString=newString+str.charAt(i);//the extracted char is going to add here.
        
    }

No comments:

Post a Comment