408. Valid Word Abbreviation

LeetCode easy original: C# #csharp #easy #leetcode #string #tree #two-pointers
El texto de la tarea se traduce del ruso para el idioma seleccionado. El código no cambia.

Строку можно сократить, заменив любое количество не смежных, непустых подстрок их длинами. Длины не должны содержать ведущих нулей.

НаEjemplo, cadena "замена" может быть сокращена следующим образом (но не ограничивается этим): "s10n" ("s ubstitutio n") "sub4u4" ("sub stit u tion") "12" ("замена") "su3i1u2on" ("su bst i t u ti on") "substitution" (без замены подстрок) Следующие сокращения не являются допустимыми:

"s55n" ("s ubsti tutio n", заменяемые подстроки смежные) "s010n" (содержит ведущие нули) "s0ubstitution" (заменяет пустую подстроку) Если заgiven строковое слово и аббревиатура abbr, return, соответствует ли cadena заданной аббревиатуре.

substring - это непрерывная непустая последовательность символов в строке.

Ejemplo:

Input: word = "internationalization", abbr = "i12iz4n"

Output: true

C# solución

coincidente/original
public class Solution {
    public bool ValidWordAbbreviation(string word, string abbr) {
        int i = 0, j = 0;
        while (i < word.Length && j < abbr.Length) {
            if (char.IsDigit(abbr[j])) {
                if (abbr[j] == '0') {
                    return false;
                }
                int num = 0;
                while (j < abbr.Length && char.IsDigit(abbr[j])) {
                    num = num * 10 + (abbr[j] - '0');
                    j++;
                }
                i += num;
            } else {
                if (word[i] != abbr[j]) {
                    return false;
                }
                i++;
                j++;
            }
        }
        return i == word.Length && j == abbr.Length;
    }
}

C++ solución

borrador automático, revisar antes de enviar
#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 ValidWordAbbreviation(string word, string abbr) {
        int i = 0, j = 0;
        while (i < word.size() && j < abbr.size()) {
            if (char.IsDigit(abbr[j])) {
                if (abbr[j] == '0') {
                    return false;
                }
                int num = 0;
                while (j < abbr.size() && char.IsDigit(abbr[j])) {
                    num = num * 10 + (abbr[j] - '0');
                    j++;
                }
                i += num;
            } else {
                if (word[i] != abbr[j]) {
                    return false;
                }
                i++;
                j++;
            }
        }
        return i == word.size() && j == abbr.size();
    }
}

Java solución

coincidente/original
public class Solution {
    public boolean validWordAbbreviation(String word, String abbr) {
        int i = 0, j = 0;
        while (i < word.length() && j < abbr.length()) {
            if (Character.isDigit(abbr.charAt(j))) {
                if (abbr.charAt(j) == '0') {
                    return false;
                }
                int num = 0;
                while (j < abbr.length() && Character.isDigit(abbr.charAt(j))) {
                    num = num * 10 + abbr.charAt(j) - '0';
                    j++;
                }
                i += num;
            } else {
                if (word.charAt(i) != abbr.charAt(j)) {
                    return false;
                }
                i++;
                j++;
            }
        }
        return i == word.length() && j == abbr.length();
    }
}

JavaScript solución

coincidente/original
function validWordAbbreviation(word, abbr) {
    let i = 0, j = 0;
    while (i < word.length && j < abbr.length) {
        if (!isNaN(abbr[j])) {
            if (abbr[j] === '0') return false;
            let num = 0;
            while (j < abbr.length && !isNaN(abbr[j])) {
                num = num * 10 + Number(abbr[j]);
                j++;
            }
            i += num;
        } else {
            if (word[i] !== abbr[j]) return false;
            i++;
            j++;
        }
    }
    return i === word.length && j === abbr.length;
}

Python solución

coincidente/original
def validWordAbbreviation(word, abbr):
    i = j = 0
    while i < len(word) and j < len(abbr):
        if abbr[j].isdigit():
            if abbr[j] == '0':
                return False
            num = 0
            while j < len(abbr) and abbr[j].isdigit():
                num = num * 10 + int(abbr[j])
                j += 1
            i += num
        else:
            if word[i] != abbr[j]:
                return False
            i += 1
            j += 1
    return i == len(word) and j == len(abbr)

Go solución

coincidente/original
package main

import (
    "strconv"
    "unicode"
)

func validWordAbbreviation(word string, abbr string) bool {
    i, j := 0, 0
    for i < len(word) && j < len(abbr) {
        if unicode.IsDigit(rune(abbr[j])) {
            if abbr[j] == '0' {
                return false
            }
            num := 0
            for j < len(abbr) && unicode.IsDigit(rune(abbr[j])) {
                n, _ := strconv.Atoi(string(abbr[j]))
                num = num*10 + n
                j++
            }
            i += num
        } else {
            if word[i] != abbr[j] {
                return false
            }
            i++
            j++
        }
    }
    return i == len(word) && j == len(abbr)
}

Algorithm

Инициализируйте два указателя: один для строки word и один для аббревиатуры abbr. Начните сравнение символов строки и аббревиатуры с начала.

Если символ аббревиатуры - это цифра, вычислите полное number и переместите указатель строки word на это количество символов. Если символ аббревиатуры - это буква, убедитесь, что он совпадает с текущим символом строки.

Повторяйте шаг 2, пока оба указателя не достигнут конца строки и аббревиатуры соответственно. Если это так, return true, иначе false.

😎

Vacantes para esta tarea

Se muestran vacantes activas con etiquetas coincidentes.

Todas las vacantes
Todavía no hay vacantes activas.