408. Valid Word Abbreviation

LeetCode easy original: C# #csharp #easy #leetcode #string #tree #two-pointers
题目文本会按所选界面语言从俄语翻译;代码保持不变。

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

На示例, 字符串 "замена" может быть сокращена следующим образом (но не ограничивается этим): "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, соответствует ли 字符串 заданной аббревиатуре.

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

示例:

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

Output: true

C# 解法

匹配/原始
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++ 解法

自动草稿,提交前请检查
#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 解法

匹配/原始
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 解法

匹配/原始
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 解法

匹配/原始
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 解法

匹配/原始
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.

😎

Vacancies for this task

活跃职位 with overlapping task tags are 已显示.

所有职位
目前还没有活跃职位。