欢迎访问yhm138的博客园博客, 你可以通过 [RSS] 的方式持续关注博客更新

MyAvatar

yhm138

HelloWorld!

【LeetCode2185】[C++/Java/Py/C#/Ruby/Swift/Go/Scala/Kotlin/Rust/PHP/TS/Elixir/Dart/Racket/Erlang] 统计包含给定前缀的字符串

题解地址

https://leetcode.cn/problems/counting-words-with-a-given-prefix/solutions/2050442/by-yhm138_-jlr3/

脚本分享

LeetCode题解区域的代码编辑器(Markdown)支持这样的语法:分tab展示不同编程语言的代码
但是如果达到大概15个tab时,底部并没有出现水平滚动条,不方便用户查看。

我写了个脚本,添加了水平滚动条来解决这个问题。

代码

cpp

//C++
class Solution {
public:
    int prefixCount(vector<string>& words, string pref) {
        return std::count_if(words.begin(), 
                             words.end(),
                             [&](auto s) { return s.find(pref) == 0; }
                            );
    }
};

java

//java
class Solution {
    public int prefixCount(String[] words, String pref) {
        return (int) Arrays.stream(words)
            .filter(word -> word.startsWith(pref))
            .count();
    }
}

python3

class Solution:
    def prefixCount(self, words: List[str], pref: str) -> int:
        return len(list(filter(lambda x: x.startswith(pref), words)))

C#

//c#
using System.Linq;

public class Solution {
    public int PrefixCount(string[] words, string pref) {
        return words.Count(word => word.StartsWith(pref));
    }
}

ruby

# ruby


# @param {String[]} words
# @param {String} pref
# @return {Integer}
def prefix_count(words, pref)
    words.count { |word| word.start_with?(pref) }
end

swift

//swift
class Solution {
    func prefixCount(_ words: [String], _ pref: String) -> Int {
        return words.filter { $0.starts(with: pref) }.count
    }
}

golang

//golang
func prefixCount(words []string, pref string) int {
	return len(filter(words, func(word string) bool {
		return strings.HasPrefix(word, pref)
	}))
}

func filter(vs []string, f func(string) bool) []string {
	vsf := make([]string, 0)
	for _, v := range vs {
		if f(v) {
			vsf = append(vsf, v)
		}
	}
	return vsf
}

scala

//scala 

object Solution {
    def prefixCount(words: Array[String], pref: String): Int = {
        return words.count(_.startsWith(pref));
    }
}

kotlin

//kotlin


class Solution {
    fun prefixCount(words: Array<String>, pref: String): Int {
        return words.count { it.startsWith(pref) }
    }
}

rust

//rust

impl Solution {
    pub fn prefix_count(words: Vec<String>, pref: String) -> i32 {
        words.iter().filter(|word| word.starts_with(&pref)).count() as i32
    }
}

php

//php

class Solution {

    /**
     * @param String[] $words
     * @param String $pref
     * @return Integer
     */
    function prefixCount($words, $pref) {
        return count(array_filter($words, function($word) use ($pref) {
            return strpos($word, $pref) === 0;
        }));
    }
}

typescript

//typescript

function prefixCount(words: string[], pref: string): number {
    return words.filter(word => word.startsWith(pref)).length;
};

elixir

# elixir

defmodule Solution do
  @spec prefix_count(words :: [String.t], pref :: String.t) :: integer
  def prefix_count(words, pref) do
    Enum.count(words, fn(word) -> String.starts_with?(word, pref) end)
  end
end

dart

//dart

class Solution {
  int prefixCount(List<String> words, String pref) {
    return words.where((word) => word.startsWith(pref)).length;
  }
}

racket

(define/contract (prefix-count words pref)
  (-> (listof string?) string? exact-integer?)
    (displayln (format "(string-prefix?  \"apple\" \"app\")=~a"  (string-prefix?  "apple" "app")  ))
    (displayln (format "(string-prefix?  \"app\" \"apple\")=~a"  (string-prefix?  "app" "apple")  ))
    (count  (lambda (word) (string-prefix? word pref)) words)
  )

; 不是,你这chatgpt连string-prefix? 入参的顺序都不知道???

erlang

% -import(binary).
% -import(unicode).



my_prefix([], _) -> true;
my_prefix([Ch | Rest1], [Ch | Rest2]) ->
        my_prefix(Rest1, Rest2);
my_prefix(_, _) -> false.



-spec prefix_count(Words :: [unicode:unicode_binary()], Pref :: unicode:unicode_binary()) -> integer().
prefix_count(Words, Pref) ->
    length(lists:filter(fun(Word) -> 
                            my_prefix(unicode:characters_to_list(Pref),unicode:characters_to_list(Word))  
                        end, Words)).

  
% 注意这里字符串用unicode_binary表示。
% erlang中字符串相关的list of bytes,unicode_binary,utf8_binary,list of code points的解析看这个帖子 https://stackoverflow.com/questions/19211584/unicodecharacters-to-list-seems-doesnt-work-for-utf8-list
% 下面是草稿
% io:write( binary:longest_common_prefix([<<"erlang">>, <<"ergonomy">>]) ),


介绍Programming-Idioms

Programming-Idioms是一个教你不同语言写同一个东西的网站
https://www.programming-idioms.org/idiom/96/check-string-prefix

介绍rosettacode

rosettacode对一些经典的算法给出了不同语言的实现
https://rosettacode.org

posted @ 2023-01-08 09:35  yhm138  阅读(25)  评论(0编辑  收藏  举报