418 Sentence Screen Fitting

T: O(rows*max of word length)

S: O(all words total length)

class Solution {
    public int wordsTyping(String[] sentence, int rows, int cols) {
        StringBuilder sb = new StringBuilder();
        for (String s : sentence) {
            sb.append(s + " ");
        }
        String s = sb.toString();
        int len = s.length();
        
        int cursor = 0;
        for (int i = 0; i < rows; i++) {
            cursor += cols;
            
            if (s.charAt(cursor%len) == ' ') {
                cursor++;
            } else {
                while (cursor >= 0 && s.charAt(cursor%len) != ' ') {
                    cursor--;
                }
                cursor++;
            }
        }
        return cursor/len;
    }
}

more concise version

class Solution {
    public int wordsTyping(String[] sentence, int rows, int cols) {
        StringBuilder sb = new StringBuilder();
        for (String s : sentence) {
            // if (s.length() > cols) { // notice this case, so if we only make idx min is 0 (idx >= 0)
            //     return 0;
            // }
            sb.append(s + " ");
        }
        String sentenceStr = sb.toString();
        int len = sentenceStr.length();
        
        int idx = 0;
        for (int i = 0; i < rows; i++) {
            idx += cols;
            while (idx >= 0 && sentenceStr.charAt(idx%len) != ' ') { // make idx min is 0, in the last idx/len = 0
                idx--;
            }
            idx++;
        }
        return idx/len;
    }
}

ๆœ€็ฐกๆฝ”็š„ๅฏซๆณ•, use String.join(" ", str)

class Solution {
    public int wordsTyping(String[] sentence, int rows, int cols) {
        String s = String.join(" ", sentence) + " ";
        int len = s.length();
        
        int idx = 0;
        for (int i = 0; i < rows; i++) {
            idx += cols;
            while (idx >= 0 && s.charAt(idx%len) != ' ') { // make idx min is 0, in the last idx/len = 0
                idx--;
            }
            idx++;
        }
        return idx/len;
    }
}

้€™้กŒ็š„้€™ๅ€‹ๅฏซๆณ•็š„ๆƒณๆณ•, ็›ธ็•ถ tricky

ex:

Input: sentence = ["a", "bcd", "e"], rows = 3, cols = 6

ๆฆ‚ๅฟต่ฝ‰ๆ›ๆˆๅƒๆ˜ฏๅœจไธ€ๅ€‹็„ก็ชฎ็š„ๅคšๅ€‹ sentence ็ต„ๆˆ็š„้•ท sentences ไธŠไปฅ row ็š„้•ทๅบฆไพ†ๅšๆ–ทๅฅ

Last updated