classSolution {publicintwordsTyping(String[] sentence,int rows,int cols) {StringBuilder sb =newStringBuilder();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)
classSolution {publicintwordsTyping(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; }}