408. Valid Word Abbreviation
Строку можно сократить, заменив любое количество не смежных, непустых подстрок их длинами. Длины не должны содержать ведущих нулей.
НаBeispiel, Zeichenkette "замена" может быть сокращена следующим образом (но не ограничивается этим): "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, соответствует ли Zeichenkette заданной аббревиатуре.
substring - это непрерывная непустая последовательность символов в строке.
Beispiel:
Input: word = "internationalization", abbr = "i12iz4n"
Output: true
C# Lösung
zugeordnet/originalpublic 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++ 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 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 Lösung
zugeordnet/originalpublic 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 Lösung
zugeordnet/originalfunction 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 Lösung
zugeordnet/originaldef 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 Lösung
zugeordnet/originalpackage 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.
😎
Stellen zu dieser Aufgabe
aktive Stellen with overlapping task tags are angezeigt.