Saturday, August 24, 2013

replace parts of the string

/*
 Challenge Description:

 Given a string S, and a list of strings of positive length, F1,R1,F2,R2,...,FN,RN,
 proceed to find in order the occurrences (left-to-right) of Fi in S and replace them with Ri. All strings are over alphabet { 0, 1 }.
 Searching should consider only contiguous pieces of S that have not been subject to replacements on prior iterations.
 An iteration of the algorithm should not write over any previous replacement by the algorithm.

 Input sample:

 Your program should accept as its first argument a path to a filename.
 Each line in this file is one test case. Each test case will contain a string, then a semicolon and then a list of comma separated strings.
 E.g. 10011011001;0110,1001,1001,0,10,11
 */
import java.io.*;

class BadFileException extends Exception{
      private static final long serialVersionUID = 1L;
     
      public String toString() {
          return "Size of Fn not equal to size of Rn!";
      }
}

public class Main {  
      public static void main(String args[]){
           if (args.length != 1) {
                System.out.println("Error: Bad command. Please enter filename.");
                System.exit(0);
           }
           Main task = new Main();
           task.stringModification(args[0]);
      }
     
      private String S;
     
      public void stringModification(String fileName) {
           BufferedReader reader = null;
        String strLine = "";
        try {
            reader = new BufferedReader(new FileReader(fileName));
            while ((strLine = reader.readLine()) != null){
                 try {
                      replaceOneLine(strLine);
                 } catch (BadFileException e) {
                      System.err.println(e.toString());
                 }
            }
        } catch (FileNotFoundException e) {
            System.err.println("Fail to find file");
        } catch (IOException e) {
            System.err.println("Fail to read file");
        }       
      }

      private void replaceOneLine(String str) throws BadFileException {
          String line = str;
           int pos = line.indexOf(";");
           S = line.substring(0, pos);
           line = line.replace(S+";", "");
          String [] FnRn = line.split(",");
           if (FnRn.length % 2 != 0) { // Each Fi & Ri comes in pair, so size of FnRn should be even.
                 throw new BadFileException();
           }
           for (int i = 0; i < FnRn.length; i += 2) {       
                 replaceFiWithRi(FnRn[i], FnRn[i+1]);
           }
          /* Re-convert 2 to 0 and 3 to 1. */
           S = S.replaceAll("2", "0");
           S = S.replaceAll("3", "1");
          System.out.println(S);
      }
     
      private void replaceFiWithRi(String Fi, String Ri) {
           /* Temporarily convert 0 in Ri to 2, and 1 to 3,
           so that later replacement will not write over any previous replacement. */
           Ri = Ri.replaceAll("0", "2");
           Ri = Ri.replaceAll("1", "3");
           S = S.replace(Fi, Ri);
      }
}



longest substring without any repetition of characters


I'm not using java very often. This program serves as a good practice for playing with String and Hashtable in java.


/* Write a code to find out longest substring without any repetition of characters with O(n) complexity. */
import java.util.*;

public class longestSubstring {
     public static String longestsubstr(String s) {
         Hashtable<Character, Integer> visited = new Hashtable<Character, Integer> ();
         String sub = new String();
         int start = 0;
         for (int i = 0; i < s.length(); ++i) {
              if (visited.containsKey(s.charAt(i))) {
                   if (i-start > sub.length()) {
                       sub = s.substring(start, i);                      
                   }
                   for (int j = start; j < visited.get(s.charAt(i)); ++j) {
                       visited.remove(s.charAt(j));
                   }
                   start = visited.get(s.charAt(i)) + 1;
                   visited.put(s.charAt(i), i);
              } else {
                   visited.put(new Character(s.charAt(i)), i);                                     
              }
         }
         if (s.length() - start > sub.length()) {
              sub = s.substring(start, s.length());
         }
         return sub;
     }
    
     public static void main(String args[]) {
         String str = "aaa1234abcde";
         System.out.println(longestsubstr(str));
         String str2 = "0123456756777890123456";
         System.out.println(longestsubstr(str2));        
     }

}