word wrap

给一个word list 和最大的长度,要求把这些word用 - 串联起来,但不能超过最大的长度。

public class Main {

    public String wordWrap(String[] words, int maxLen)
    {
        if(words == null || words.length == 0)
        {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        int current = 0;
        int remain = maxLen;
        for(int i = 0; i< words.length; i++)
        {
            if(words[i].length > remain)
            {
                break;
            }
            sb.append(words[i]).append("-");
            remain -= words[i].length + 1;

        }
        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }
    
}

Last updated