2013년 12월 7일 토요일

Longest Common Prefix


 public String longestCommonPrefix(String[] strs) {
  if (strs == null)
   return null;

  int len = strs.length;
  if (len == 0)
   return "";

  int shortStrIdx = 0;
  int shortStrLen = strs[0].length();
  for (int i = 1; i < len; i++) {
   int strLen = strs[i].length();
   if (strLen < shortStrLen) {
    shortStrIdx = i;
    shortStrLen = strLen;
   } else if (strLen == shortStrLen) {
    for (int j = 0; j < strLen; j++) {
     if (strs[shortStrIdx].charAt(j) != strs[i].charAt(j)) {
      shortStrLen = j;
      break;
     }
    }
    if (shortStrLen == 0)
     return "";
   }
  }

  for (int i = 0; i < len; i++) {
   if (i == shortStrIdx)
    continue;

   for (int j = 0; j < shortStrLen; j++) {
    if (strs[shortStrIdx].charAt(j) != strs[i].charAt(j)) {
     shortStrLen = j;
     break;
    }
    if (shortStrLen == 0)
     return "";
   }
  }

  return strs[shortStrIdx].substring(0, shortStrLen);
 }

댓글 없음:

댓글 쓰기