similar_text
similar_text(string $string1, string $string2, &$percent = null): int
计算两字符串相似度:返回共同字符数,可选引用参数输出百分比(2×共同/(长1+长2)×100);与 levenshtein 构成「相似度 vs 编辑距离」双算法。
C C23
#include <stdio.h>
#include <string.h>
/* 最长公共子序列(LCS),再套 PHP 的百分比公式:
pct = 2 * L * 100 / (len1 + len2) */
static int lcs(const char *a, const char *b) {
int la = (int)strlen(a), lb = (int)strlen(b);
int dp[16][16] = { { 0 } };
for (int i = 1; i <= la; i++)
for (int j = 1; j <= lb; j++)
dp[i][j] = a[i-1] == b[j-1] ? dp[i-1][j-1] + 1
: (dp[i-1][j] > dp[i][j-1] ? dp[i-1][j] : dp[i][j-1]);
return dp[la][lb];
}
int main(void) {
printf("%d\n", lcs("hello", "hallo")); /* 4 */
printf("%d\n", lcs("kitten", "mitten")); /* 5 */
return 0;
}
4 5
C++ C++26
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
static int lcs(const std::string& a, const std::string& b) {
std::vector<std::vector<int>> dp(a.size() + 1, std::vector<int>(b.size() + 1, 0));
for (size_t i = 1; i <= a.size(); i++)
for (size_t j = 1; j <= b.size(); j++)
dp[i][j] = a[i-1] == b[j-1] ? dp[i-1][j-1] + 1
: std::max(dp[i-1][j], dp[i][j-1]);
return dp[a.size()][b.size()];
}
int main() {
std::cout << lcs("hello", "hallo") << "\n"; // 4
std::cout << lcs("kitten", "mitten") << "\n"; // 5
return 0;
}
4 5
C# v11.0.100
class MainClass {
static int Lcs(string a, string b) {
var dp = new int[a.Length + 1, b.Length + 1];
for (int i = 1; i <= a.Length; i++)
for (int j = 1; j <= b.Length; j++)
dp[i, j] = a[i-1] == b[j-1] ? dp[i-1, j-1] + 1
: System.Math.Max(dp[i-1, j], dp[i, j-1]);
return dp[a.Length, b.Length];
}
static void Main() {
System.Console.WriteLine(Lcs("hello", "hallo")); // 4
System.Console.WriteLine(Lcs("kitten", "mitten")); // 5
}
}
4 5
Go v1.27.4
package main
import "fmt"
// LCS 动态规划;PHP 的百分比公式是
// pct = 2*L*100/(len1+len2)——与 difflib 的 ratio 同一公式
func lcs(a, b string) int {
dp := make([][]int, len(a)+1)
for i := range dp {
dp[i] = make([]int, len(b)+1)
}
for i := 1; i <= len(a); i++ {
for j := 1; j <= len(b); j++ {
if a[i-1] == b[j-1] {
dp[i][j] = dp[i-1][j-1] + 1
} else if dp[i-1][j] > dp[i][j-1] {
dp[i][j] = dp[i-1][j]
} else {
dp[i][j] = dp[i][j-1]
}
}
}
return dp[len(a)][len(b)]
}
func main() {
fmt.Println(lcs("hello", "hallo")) // 4
fmt.Println(lcs("kitten", "mitten")) // 5
}
4 5
Java v27.0.1
class Main {
static int lcs(String a, String b) {
int[][] dp = new int[a.length() + 1][b.length() + 1];
for (int i = 1; i <= a.length(); i++)
for (int j = 1; j <= b.length(); j++)
dp[i][j] = a.charAt(i-1) == b.charAt(j-1)
? dp[i-1][j-1] + 1
: Math.max(dp[i-1][j], dp[i][j-1]);
return dp[a.length()][b.length()];
}
public static void main(String[] args) {
System.out.println(lcs("hello", "hallo")); // 4
System.out.println(lcs("kitten", "mitten")); // 5
}
}
4 5
JavaScript v26.13.1
function lcs(a, b) {
const dp = Array.from({ length: a.length + 1 }, () =>
new Array(b.length + 1).fill(0)
);
for (let i = 1; i <= a.length; i++)
for (let j = 1; j <= b.length; j++)
dp[i][j] = a[i-1] === b[j-1] ? dp[i-1][j-1] + 1 : Math.max(dp[i-1][j], dp[i][j-1]);
return dp[a.length][b.length];
}
console.log(lcs("hello", "hallo")); // 4
console.log(lcs("kitten", "mitten")); // 5
4 5
PHP v8.6.0
// Oliver 算法:递归最长公共子串,不是 LCS
similar_text("hello", "hallo", $p);
echo similar_text("hello", "hallo"), " ", round($p, 2), "\n"; // 4 80
similar_text("kitten", "mitten", $p2);
echo similar_text("kitten", "mitten"), " ", round($p2, 2), "\n"; // 5 83.33
4 80 5 83.33
Python v3.15.2
from difflib import SequenceMatcher
# SequenceMatcher 与 PHP 百分比同一公式:2*M/(len1+len2)。
# 但匹配算法不同(Ratcliff/Obershelp vs PHP 递归最长公共子串)
# ——数值可能有分歧。
m = SequenceMatcher(None, "hello", "hallo")
print(m.ratio() * 100) # 80.0
m2 = SequenceMatcher(None, "kitten", "mitten")
print(round(m2.ratio() * 100, 2)) # 83.33
80.0 83.33
Rust v1.99.1
fn lcs(a: &str, b: &str) -> usize {
let a: Vec<char> = a.chars().collect();
let b: Vec<char> = b.chars().collect();
let mut dp = vec![vec![0usize; b.len() + 1]; a.len() + 1];
for i in 1..=a.len() {
for j in 1..=b.len() {
dp[i][j] = if a[i-1] == b[j-1] {
dp[i-1][j-1] + 1
} else {
dp[i-1][j].max(dp[i][j-1])
};
}
}
dp[a.len()][b.len()]
}
fn main() {
println!("{}", lcs("hello", "hallo")); // 4
println!("{}", lcs("kitten", "mitten")); // 5
}
4 5
TypeScript v26.13.1
function lcs(a: string, b: string): number {
const dp: number[][] = Array.from({ length: a.length + 1 }, () =>
new Array(b.length + 1).fill(0)
);
for (let i = 1; i <= a.length; i++)
for (let j = 1; j <= b.length; j++)
dp[i][j] = a[i-1] === b[j-1] ? dp[i-1][j-1] + 1 : Math.max(dp[i-1][j], dp[i][j-1]);
return dp[a.length][b.length];
}
console.log(lcs("hello", "hallo")); // 4
console.log(lcs("kitten", "mitten")); // 5
4 5
语言差异说明
C:固定大小 dp[16][16] = {{0}}(示例,铁律清零);实际使用按串长动态 malloc 或限长;「百分比」用整数运算 2*L*100/(la+lb) 即得(hello/hallo → 80)。
C++:vector<vector<int>> 动态 DP(示例);串长未知的场景注意 size_t 无符号下溢(i-1 当 i=0),从 1 起循环回避;std::max 需 <algorithm>。
C#:二维数组语法 dp[i, j](示例);与 levenshtein 条目同构——把「min」换「max」、把「不等加一」换「相等加一」就是两个算法的全部差异。
Go:切片 DP(示例);PHP 的 pct 公式与 Python difflib 的 ratio 完全同一公式(2M/T),跨语言可对照;Go 无内建相似度,标准做法手写 LCS/Levenshtein。
Java:经典二维 DP(示例);charAt O(1) 访问;JDK 无内建相似度,Apache Commons Lang 的 StringUtils.getSimilarity(Levenshtein 系)是生态常用。
JavaScript:Array.from + fill 建表(示例);注意 new Array(n).fill(0) 必须先 fill 再用(稀疏数组 map 陷阱);与 PHP 一样无内建——npm 的 natural/工包或手写。
PHP:算法是 Oliver 1993 递归最长公共子串(示例注释)——不是教科书 LCS;共同字符数 + 引用参数百分比(公式 2×count/(len1+len2)×100,实测 hello/hallo=4/80、kitten/mitten=5/83.33);与 A16 levenshtein 条目成对:相似度数「共同」,距离数「代价」;O(len1×len2) 递归深串注意栈。
Python:difflib.SequenceMatcher.ratio()(示例)与 PHP 百分比同公式、本例同值——但算法(Ratcliff/Obershelp 最长匹配块递归)与 PHP 的 Oliver 不同,一般字符串上数值可以不同,勿假设跨语言一致;get_matching_blocks() 可拿对齐块。
Rust:vec! 建 DP 表(示例);chars() 按 code point 迭代,Unicode 安全;无内建相似度,crates(strsim)提供 Jaro/Levenshtein 系。
TypeScript:同 JS(示例);number[][] 显式类型;生产环境建议封装为工具函数并加复杂度注释——O(len1×len2) 对长串危险。