본문 바로가기

서적/리트코드

C# 리트코드 14. Longest Common Prefix

728x90
반응형

Approach 1: Horizontal scanning

public class Solution
{
  public string LongestCommonPrefix(string[] strs)
  {
    if(strs.Length == 0) return "";
    
    string prefix = strs[0];

    for (int i = 1; i < strs.Length; i++)
    {
      while(strs[i].IndexOf(prefix) != 0)
      {
        prefix = prefix.Substring(0, prefix.Length - 1);
        if (string.IsNullOrEmpty(prefix)) return "";
      }
    }
    return prefix;
  }
}

Approach 2: Vertical scanning

public class Solution
{
  public string LongestCommonPrefix(string[] strs)
  {
    if(strs.Length == 0) return "";
    
    for (int i = 1; i < strs[0].Length; i++)
    {
      for (int j = 1; j < strs.Length; j++)
      {
        if (i == strs[j].Length || strs[j][i] != strs[0][i])
          return strs[0].Substring(0, i);
      }
    }
    return strs[0];
  }
}
str.charAt(8); // In Java, you would say
str[8]; // In C#, you would say
728x90
반응형

'서적 > 리트코드' 카테고리의 다른 글

C# 리트코드 20. Valid Parentheses  (0) 2022.01.19
C# 리트코드 13. Roman to Integer  (0) 2022.01.16
C# 리트코드 1. Two Sum  (0) 2022.01.13