Leetcode/Top Interview 150

[Array/String][Hard] 68. Text Justification

자전거통학 2024. 5. 3. 02:24

https://leetcode.com/problems/text-justification/description

 

Q. 단어 집한 words가 주어진다. 이때 maxWidth와 규칙에 맞게 string을 출력하라. 

 

Solution. 

 마지막 라인의 규칙 때문에 조금 예외처리가 들어가는 문제. 

 

 로직 자체는 큰 어려움이 없으나, 상황에 따른 처리들이 조금 필요하다. 

 

 코드 

더보기

 

string getLine(string[] words, ref int idxStart, int maxWidth)
{
    int len = 0;
    int idx = idxStart;
    List<int> spaces = new List<int>();
    for(; idx < words.Length; ++idx)
    {
        len += words[idx].Length;
        if(len > maxWidth)
        {
            spaces.RemoveAt(spaces.Count-1);
            len -= words[idx].Length;
            len--;  // remove last space as well.
            break;
        }
        spaces.Add(len<maxWidth ? 1 : 0);
        ++len;
    }
    if(len == 0)    return "";


    bool isLastLine = idx==words.Length;
    // Console.WriteLine("Cut : " + spaces.Count + " , " + len + ", " + idx + " , " + isLastLine);

    if(!isLastLine && spaces.Count==0)
        spaces.Add(0);

    string line = "";

    int iSpace = 0;
    while(spaces.Count>0 && len<maxWidth)
    {
        if(isLastLine)
            iSpace = spaces.Count-1;
        else iSpace %= spaces.Count;
        spaces[iSpace++]++;
        ++len;
    }

    //for(int q = 0; q < spaces.Count; ++q)
    //     Console.WriteLine("Spaces : " + spaces[q]);

    iSpace = 0;
    for(int q = idxStart; q < idx; ++q)
    {
        line += words[q];
        if(iSpace < spaces.Count)
        {
            for(int z = 0; z < spaces[iSpace]; ++z)
               line += " ";
            ++iSpace;
        }
    }
    idxStart = idx;
    return line;
}

public IList<string> FullJustify(string[] words, int maxWidth) 
{
    IList<string> ret = new List<string>();
    int idx = 0;
    string line = getLine(words, ref idx, maxWidth);
    while(!string.IsNullOrEmpty(line))
    {
        ret.Add(line);
        line = getLine(words, ref idx, maxWidth);
    }
    return ret;
}

 

 

 

 기회가 되면 로직을 더 다듬어 본다.  

 

 결과는 적당.