[leetcode]806. Number of Lines To Write String

[leetcode]806. Number of Lines To Write String


Analysis

old friends~—— [嘻嘻~]

We are to write the letters of a given string S, from left to right into lines. Each line has maximum width 100 units, and if writing a letter would cause the width of the line to exceed 100 units, it is written on the next line. We are given an array widths, an array where widths[0] is the width of ‘a’, widths[1] is the width of ‘b’, …, and widths[25] is the width of ‘z’.
Now answer two questions: how many lines have at least one character from S, and what is the width used by the last such line? Return your answer as an integer list of length 2.
遍历字符串,按照他的要求一行一行的写,然后判断最后一个字符在哪一行哪一列就行了

Implement

class Solution {
public:
    vector<int> numberOfLines(vector<int>& widths, string S) {
        vector<int> res;
        int len = S.length();
        int line = 1;
        int pos = 0;
        int tmp;
        for(int i=0; i<len; i++){
            pos += widths[S[i]-'a'];
            if(pos > 100){
                line++;
                pos = 0;
                i--;
            }
        }
        res.push_back(line);
        res.push_back(pos);
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81253379
今日推荐