int* numberOfLines(int* widths, int widthsSize, char * s, int* returnSize){ int lines = 1; int width = 0; int len = strlen(s); for (int i = 0; i < len; i++) { int need = widths[s[i] - 'a']; width += need; if (width > MAX_WIDTH) { lines++; width = need; } } int * ans = (int *)malloc(sizeof(int) * 2); *returnSize = 2; ans[0] = lines; ans[1] = width; return ans; }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13
funcnumberOfLines(widths []int, s string) []int { const maxWidth = 100 lines, width := 1, 0 for _, c := range s { need := widths[c-'a'] width += need if width > maxWidth { lines++ width = need } } return []int{lines, width} }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
constMAX_WIDTH = 100; var numberOfLines = function(widths, s) { let lines = 1; let width = 0; for (let i = 0; i < s.length; i++) { const need = widths[s[i].charCodeAt() - 'a'.charCodeAt()]; width += need; if (width > MAX_WIDTH) { lines++; width = need; } } return [lines, width]; };