LeetCode--Number of Lines To Write String

思路:

    遍历字符串中的所有字符,依次将其对应的大小相加,如果遇到不够格的情况,则换到下一行,最后返回行数和最后一行的空间数.

class Solution {
    public int[] numberOfLines(int[] widths, String S) {
        int[] res=new int[]{0,0};
        if(S.length()>0){
            res[0]++;
        }
        else{
            return res;
        }
        for(int i=0;i<S.length();i++){
            char c=S.charAt(i);
            int pos=c-97;
            if(res[1]+widths[pos]>100){
                res[0]++;
                res[1]=widths[pos];
            }
            else{
                res[1]+=widths[pos];
            }
        }
        
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_21752135/article/details/80032202