2255. Count Prefixes of a Given String

2023. 1. 26. 22:44Algorithm/Leetcode, Lintcode, HackerRank, etc.

    목차
반응형

Kotlin

class Solution {
    fun countPrefixes(words: Array<String>, s: String): Int {
        var cnt = 0

        for (word in words) {
            if (word.length > s.length) {
                continue
            }

            var is_same = true

            for (i in 0 .. word.length - 1) {
                if (word[i] != s[i]) {
                    is_same = false
                    break
                }
            }

            if (true == is_same) {
                cnt += 1
            }
        }

        return cnt
    }
}

Python

class Solution:
    def countPrefixes(self, words: List[str], s: str) -> int:
        cnt = 0

        for word in words:
            if len(word) > len(s):
                continue

            for i in range(0, len(word)):
                if word[i] != s[i]:
                    break
            else:
                cnt += 1

        return cnt

C++

class Solution {
public:
    int countPrefixes(vector<string>& words, string s) {
        int cnt = 0;

        for (const auto &word : words) {
            if (word.size() > s.size()) {
                continue;
            }

            bool is_same = true;

            for (auto i = 0; i < word.size(); ++i) {
                if (word[i] != s[i]) {
                    is_same = false;
                    break;
                }
            }

            if (true == is_same) {
                cnt += 1;
            }
        }

        return cnt;
    }
};
반응형