Number of Lines To Write String


  • 0

    Click here to see the full article post


  • 0
    V

    the solution provided by leetcode does not account for if the string S is an empty string in which it should return [0 ,0]. Here is my solution for this problem:

    class Solution {
        public int[] numberOfLines(int[] widths, String S) {
            if(S.length() == 0){
                return new int[] {0,0};
            }
            int units = 0;
            int line = 1;
            for(char c: S.toCharArray()){
                if(units + widths[c - 'a'] > 100){
                    line += 1;
                    units = widths[c - 'a'];
                }else if(units + widths[c - 'a'] == 100){
                    line += 1;
                    units = 0;
                }else{
                    units += widths[c -'a'];
                }
            }
            return new int[] {line, units};
        }
    }

  • 0
    J

    @veraateeq Dude, read the note first


  • 0
    I
    This post is deleted!

  • 0
    Z
    public int[] numberOfLines(int[] widths, String S) {
        int[] out = new int[]{1,0};
        int n = 0;
        for(char c: S.toCharArray()) {
           if (c > 'z' || c < 'a') continue;
           n += widths[c-'a'];
           if (n > 100) {
               n = widths[c-'a'];
               out[0]++;
           }
        }
        out[1] = n;
        return out;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.