JS,Python和Java 7的学习算法:七巧板
程序员文章站
2022-05-20 22:52:33
...
This is the seventh article of my attempts to follow Stephen Grider's Udemy course in three different languages. JavaScript solutions are by Stephen. I try to "translate" it into Python and Java.
今天的问题是:
检查两个提供的字符串是否彼此相同。 One string is an anagram of another if it uses the same characters in the same quantity. Only consider characters, not spaces or punctuation. Consider capital letters to be the same as lower case --- Examples anagrams('rail safety', 'fairy tales') --> True anagrams('RAIL! SAFETY!', 'fairy tales') --> True anagrams('Hi there', 'Bye there') --> False
1:计算每个字母
JavaScript:
function anagrams(stringA, stringB) {
const charMapA = buildCharMap(stringA);
const charMapB = buildCharMap(stringB);
if (Object.keys(charMapA).length !== Object.keys(charMapB).length) {
return false;
}
for (let char in charMapA) {
if (charMapA[char] !== charMapB[char]) {
return false;
}
}
return true;
}
function buildCharMap(str) {
const charMap = {};
for (let char of str.replace(/[^\w]/g, '').toLowerCase()) {
charMap[char] = charMap[char] + 1 || 1;
}
return charMap;
}
蟒蛇:
import re
from collections import Counter
def anagrams(string_a: str, string_b: str) -> bool:
char_map_a = build_counter(string_a)
char_map_b = build_counter(string_b)
if len(char_map_a.keys()) != len(char_map_b.keys()):
return False
for char in char_map_a.keys():
if char not in char_map_b or char_map_a[char] != char_map_b[char]:
return False
return True
def build_counter(string: str) -> Counter:
return Counter(re.sub(r'[^\w]', '', string, flags=re.UNICODE).lower())
实际上,这也可行:
import re
from collections import Counter
def anagrams(string_a: str, string_b: str) -> bool:
return build_counter(string_a) == build_counter(string_b)
def build_counter(string: str) -> Counter:
return Counter(re.sub(r'[^\w]', '', string, flags=re.UNICODE).lower())
Java:
import java.util.Map;
import java.util.stream.Collectors;
public static boolean anagrams(String stringA, String stringB) {
Map<Character, Long> charMapA = buildCharMap(stringA);
Map<Character, Long> charMapB = buildCharMap(stringB);
if (charMapA.keySet().size() != charMapB.keySet().size()) {
return false;
}
for (char chr : charMapA.keySet()) {
if (!charMapB.containsKey(chr) || !charMapA.get(chr).equals(charMapB.get(chr))) {
return false;
}
}
return true;
}
private static Map<Character, Long> buildCharMap(String str) {
return str.replaceAll("[^\\w]", "")
.toLowerCase()
.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(c -> c, Collectors.counting()));
}
2:排序以进行比较
JavaScript:
function anagrams(stringA, stringB) {
return cleanString(stringA) === cleanString(stringB);
}
function cleanString(str) {
return str
.replace(/[^\w]/g, '')
.toLowerCase()
.split('')
.sort()
.join('');
}
蟒蛇:
import re
def anagrams(string_a: str, string_b: str) -> bool:
return clean_string(string_a) == clean_string(string_b)
def clean_string(string: str) -> str:
lower = re.sub(r'[^\w]', '', string, flags=re.UNICODE).lower()
return ''.join(sorted(lower))
Java:
import java.util.stream.Collectors;
public static boolean anagrams(String stringA, String stringB) {
return cleanString(stringA).equals(cleanString(stringB));
}
private static String cleanString(String str) {
return str.replaceAll("[^\\w]", "")
.toLowerCase()
.chars()
.mapToObj(i -> (char) i)
.sorted()
.map(String::valueOf)
.collect(Collectors.joining());
}
我希望你喜欢这个。 我将不胜感激任何意见和反馈。
from: https://dev.to//tommy3/learning-algorithms-with-js-python-and-java-7-anagrams-1lgf
上一篇: PSO(粒子群)算法学习笔记
下一篇: 粒子群算法案例学习-非线性函数寻优
推荐阅读
-
Hadoop学习(7)-hive的安装和命令行使用和java操作
-
python机器学习朴素贝叶斯算法及模型的选择和调优详解
-
NLP学习(四)规则分词-正向、逆向和双向最大匹配算法的中文分词-python3实现
-
Hadoop学习(7)-hive的安装和命令行使用和java操作
-
为什么在美国的cs编程入门课大多有java和python。而在国内首先学习的语言是c/c++?
-
JS,Python和Java 7的学习算法:七巧板
-
docker学习二(基于centos7镜像构建python3和nginx,uwsgi的新镜像)
-
python机器学习朴素贝叶斯算法及模型的选择和调优详解
-
mjson:像python和ruby一样好用的java类库操作json_js