418. Sentence Screen Fitting

LeetCode medium original: C# #bit-manipulation #csharp #leetcode #medium #string
Der Aufgabentext wird für die gewählte Sprache aus dem Russischen übersetzt. Code bleibt unverändert.

Если задан экран rows x cols и предложение, представленное в виде списка строк, return количество раз, которое данное предложение может быть помещено на экран. Порядок слов в предложении должен оставаться неизменным, и слово не может быть разбито на две строки. Два последовательных слова в строке должны разделяться одним пробелом.

Beispiel:

Input: sentence = ["hello","world"], rows = 2, cols = 8

Output: 1

C# Lösung

zugeordnet/original
public class Solution {
    public int WordsTyping(string[] sentence, int rows, int cols) {
        string sentenceStr = string.Join(" ", sentence) + " ";
        int length = sentenceStr.Length;
        int count = 0;
        
        for (int i = 0; i < rows; i++) {
            count += cols;
            if (sentenceStr[count % length] == ' ') {
                count++;
            } else {
                while (count > 0 && sentenceStr[(count - 1) % length] != ' ') {
                    count--;
                }
            }
        }
        
        return count / length;
    }
}

C++ Lösung

Auto-Entwurf, vor dem Einreichen prüfen
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int WordsTyping(vector<string> sentence, int rows, int cols) {
        string sentenceStr = string.Join(" ", sentence) + " ";
        int length = sentenceStr.size();
        int count = 0;
        
        for (int i = 0; i < rows; i++) {
            count += cols;
            if (sentenceStr[count % length] == ' ') {
                count++;
            } else {
                while (count > 0 && sentenceStr[(count - 1) % length] != ' ') {
                    count--;
                }
            }
        }
        
        return count / length;
    }
}

Java Lösung

zugeordnet/original
public class Solution {
    public int wordsTyping(String[] sentence, int rows, int cols) {
        String sentenceStr = String.join(" ", sentence) + " ";
        int length = sentenceStr.length();
        int count = 0;
        
        for (int i = 0; i < rows; i++) {
            count += cols;
            if (sentenceStr.charAt(count % length) == ' ') {
                count++;
            } else {
                while (count > 0 && sentenceStr.charAt((count - 1) % length) != ' ') {
                    count--;
                }
            }
        }
        
        return count / length;
    }
}

JavaScript Lösung

zugeordnet/original
function wordsTyping(sentence, rows, cols) {
    const sentenceStr = sentence.join(" ") + " ";
    const length = sentenceStr.length;
    let count = 0;
    
    for (let i = 0; i < rows; i++) {
        count += cols;
        if (sentenceStr[count % length] === " ") {
            count++;
        } else {
            while (count > 0 && sentenceStr[(count - 1) % length] !== " ") {
                count--;
            }
        }
    }
    
    return Math.floor(count / length);
}

Python Lösung

zugeordnet/original
def wordsTyping(sentence, rows, cols):
    sentence_str = " ".join(sentence) + " "
    length = len(sentence_str)
    pos = 0
    
    for _ in range(rows):
        pos += cols
        if sentence_str[pos % length] == " ":
            pos += 1
        else:
            while pos > 0 and sentence_str[(pos - 1) % length] != " ":
                pos -= 1
    
    return pos // length

Go Lösung

zugeordnet/original
package main

func wordsTyping(sentence []string, rows int, cols int) int {
    sentenceStr := ""
    for _, word := range sentence {
        sentenceStr += word + " "
    }
    length := len(sentenceStr)
    count := 0
    
    for i := 0; i < rows; i++ {
        count += cols
        if sentenceStr[count % length] == ' ' {
            count++
        } else {
            for count > 0 && sentenceStr[(count - 1) % length] != ' ' {
                count--
            }
        }
    }
    
    return count / length
}

Algorithm

Преобразуйте предложение в единую строку с пробелами между словами и пробелом в конце.

Инициализируйте переменную для отслеживания текущей позиции в строке предложения. Для каждой строки экрана добавляйте количество символов, равное числу столбцов.

Если следующая позиция является пробелом, увеличивайте счетчик. Если нет, уменьшайте счетчик, пока не найдете пробел, чтобы избежать разрыва слова.

😎

Stellen zu dieser Aufgabe

aktive Stellen with overlapping task tags are angezeigt.

Alle Stellen
Es gibt noch keine aktiven Stellen.