422. Valid Word Square

LeetCode easy original: C# #array #csharp #easy #leetcode #math #string
선택한 UI 언어에 맞게 문제 텍스트를 러시아어에서 번역합니다. 코드는 변경하지 않습니다.

Дан 배열 строк words, return true, если он образует правильный квадрат слов.

Последовательность строк образует правильный квадрат слов, если k-я 문자열 и k-й столбец читаются одинаково, где 0 <= k < max(numRows, numColumns).

예제:

Input: words = ["abcd","bnrt","crmy","dtye"]

Output: true

Explanation:

The 1st row and 1st column both read "abcd".

The 2nd row and 2nd column both read "bnrt".

The 3rd row and 3rd column both read "crmy".

The 4th row and 4th column both read "dtye".

Therefore, it is a valid word square.

C# 해법

매칭됨/원본
using System;
using System.Collections.Generic;
public class Solution {
    public bool ValidWordSquare(IList<string> words) {
        int cols = 0;
        int rows = words.Count;
        var newWords = new List<string>();
        
        foreach (var word in words) {
            cols = Math.Max(cols, word.Length);
        }
        if (cols != words[0].Length || rows != cols) {
            return false;
        }
        for (int col = 0; col < cols; ++col) {
            var newWord = string.Empty;
            for (int row = 0; row < rows; ++row) {
                if (col < words[row].Length) {
                    newWord += words[row][col];
                }
            }
            newWords.Add(newWord);
        }
        return words.SequenceEqual(newWords);
    }
}

C++ 해법

자동 초안, 제출 전 검토
#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 bool ValidWordSquare(vector<string> words) {
        int cols = 0;
        int rows = words.size();
        var newWords = new List<string>();
        
        foreach (var word in words) {
            cols = max(cols, word.size());
        }
        if (cols != words[0].size() || rows != cols) {
            return false;
        }
        for (int col = 0; col < cols; ++col) {
            var newWord = string.Empty;
            for (int row = 0; row < rows; ++row) {
                if (col < words[row].size()) {
                    newWord += words[row][col];
                }
            }
            newWords.push_back(newWord);
        }
        return words.SequenceEqual(newWords);
    }
}

Java 해법

매칭됨/원본
import java.util.*;

public class Solution {
    public boolean validWordSquare(List<String> words) {
        int cols = 0;
        int rows = words.size();
        List<String> newWords = new ArrayList<>();
        
        for (String word : words) {
            cols = Math.max(cols, word.length());
        }

        if (cols != words.get(0).length() || rows != cols) {
            return false;
        }

        for (int col = 0; col < cols; ++col) {
            StringBuilder newWord = new StringBuilder();
            for (int row = 0; row < rows; ++row) {
                if (col < words.get(row).length()) {
                    newWord.append(words.get(row).charAt(col));
                }
            }
            newWords.add(newWord.toString());
        }

        return words.equals(newWords);
    }
}

Python 해법

매칭됨/원본
class Solution:
    def validWordSquare(self, words: list[str]) -> bool:
        cols = 0
        rows = len(words)
        newWords = []
        
        for word in words:
            cols = max(cols, len(word))

        if cols != len(words[0]) or rows != cols:
            return False

        for col in range(cols):
            newWord = ""
            for row in range(rows):
                if col < len(words[row]):
                    newWord += words[row][col]
            newWords.append(newWord)

        return words == newWords

Go 해법

매칭됨/원본
package main

func validWordSquare(words []string) bool {
    cols := 0
    rows := len(words)
    newWords := []string{}
    
    for _, word := range words {
        if len(word) > cols {
            cols = len(word)
        }
    }

    if cols != len(words[0]) || rows != cols {
        return false
    }

    for col := 0; col < cols; col++ {
        newWord := ""
        for row := 0; row < rows; row++ {
            if col < len(words[row]) {
                newWord += string(words[row][col])
            }
        }
        newWords = append(newWords, newWord)
    }

    for i := range words {
        if words[i] != newWords[i] {
            return false
        }
    }
    return true
}

Algorithm

Инициализируйте переменные: cols для максимальной длины слов в 배열е, rows для количества строк в 배열е words, и пустой 배열 newWords для хранения новых слов, представленных каждым столбцом.

Итерация по 배열у words, 정의 максимальной длины слова для cols, проверка, что количество строк равно количеству столбцов. Если 문제 설명 не выполняется, возвращаем false.

Для каждого столбца col от 0 до cols - 1, формируем строку newWord из символов на позиции (row, col) для каждой строки. Сохраняем newWord в 배열е newWords. В конце, если newWords и words равны, возвращаем true, иначе false.

😎

Vacancies for this task

활성 채용 with overlapping task tags are 표시됨.

전체 채용
아직 활성 채용이 없습니다.