Thursday, August 29, 2013

1.5 ------------------- string compress

Q:
1.5 Implement a method to perform basic string compression using the counts
of repeated characters. For example, the string “aabcccccaaa” would become
“a2blc5a3”. If the "compressed" string would not become smaller than the original string, your method should return the original string.


A:
public static String compressString(String str) {

    // assume str are all ASCII

    if (str == null)

        return null;

    // check there do not exist digits

    for (int i = 0; i < str.length(); i++)

        if (isDigit(str.charAt(i))) {

            System.err.println("inputs string exist Digits");

            System.exit(-1);

        }

    // count the repeated char number

    int[] charCount = new int[str.length()];

    char lastChar = str.charAt(0);

    for (int i = 1; i < str.length(); i++) {

        if (str.charAt(i) == lastChar)

            charCount[i] = charCount[i - 1] + 1;

        else

            lastChar = str.charAt(i);

    }

    // after counting , if at most two sequence,(i.e. no compress)

    // return original

    // now, this can be compressed

    StringBuffer sbf = new StringBuffer();

    for (int i = 0; i < str.length(); i++) {

        char ch = str.charAt(i);

        if (charCount[i] == 0)

            sbf.append(ch);

        // Then, we need add the digits, instead of chars

        while (i + 1 < str.length() && charCount[i + 1] > charCount[i]) {

            i++;

        }

        sbf.append(charCount[i] + 1);

    }

    String newStr = sbf.toString();

    if (newStr.length() >= str.length())

        return str;

    else

        return newStr;

}

private static boolean isDigit(char ch) {

    if (ch <= '9' && ch >= '0')

        return true;

    else

        return false;

}



  



Mistakes:
0:  一上来,题意没看清。    例子中,"b" 后面,压缩后,为1的。
  应该仔细看题的。----------> 面试时,应该重复听到的问题。 说出自己的理解。


1:  all objects should be checked "null" , otherwise, when running, there might be some nullPointerException.
2:   系统运行,遇到error,要打印提示,并跳出的语句不会。
          这是刚刚用到的。
               System.err.println("   error message      ");
                System.exit(-1);
3:   做循环的时候,应该先判断边界问题, 再去作别的判断。
例如,上面答案里: 
      while( charCount[i+1] > charCount[i] && i+1<str.length()  )      是不对的。会有边界溢出。
应该 while(i+1<str.length() && charCount[i+1] > charCount[i] )



学到:
1:       在paper上写完,一定要自己在脑子里,把各种情况都考虑一遍。
           例如,这里,就因为开始申请的chCount 全为零, 最后StringBuffer.add(count)的时候,要加1的。
2:   

No comments:

Post a Comment