[英]How to count common characters in two strings in JavaScript?
給定兩個由小寫英文字母組成的字符串s1
和s2
,任務是計算給定字符串中的所有索引對 ( i, j
),使得s1[i] = s2[j]
並且所有索引都是不同的,即如果s1[i]
與一些s2[j]
配對,那么這兩個字符將不會與任何其他字符配對。
Input: s1 = 'abcd', s2 = 'aad'
Output: 2
Input: s1 = 'geeksforgeeks', s2 = 'platformforgeeks'
Output: 8
我試着喜歡這樣:
function getSameCount(str, str2) { var o = {}, o2 = {}; for (var i = 0; i < str.length - 1; i++) { if (str[i] in o) { o[str[i]] = parseInt(o[str[i]] + 1) } else { o[str[i]] = 0 } } console.log(o); for (var i = 0; i < str2.length - 1; i++) { if (str[i] in o2) { o2[str[i]] = parseInt(o2[str[i]] + 1) } else { o2[str[i]] = 0 } } console.log(o2); } getSameCount('abcd', 'aad')
使用for..in
循環和includes
方法
var s1 = "abcd"; var s2 = "aad"; var count=0; function match(s1,s2) { for(let i in s1) s2.includes(s1[i])?count++:false; console.log(count) } match(s1,s2)
我們可以將第二個輸入字符串轉換為數組,然后下一步是迭代第一個輸入字符串並在第二個輸入字符串的字符數組中找到匹配項。
如果找到匹配項,則增加計數器並從第二個輸入字符串的字符數組中刪除該字符,以便在下一個匹配項中不考慮它:
//Solution: function getSameCount(str1, str2) { let count = 0; const obj = str2.split(""); for(str of str1){ let idx = obj.findIndex(s => s === str); if(idx >= 0){ count++; obj.splice(idx, 1); } } return count; } //Test: console.log(getSameCount("abcd", "aad")); console.log(getSameCount("geeksforgeeks", "platformforgeeks")); console.log(getSameCount("aad", "abcd")); console.log(getSameCount("platformforgeeks", "geeksforgeeks"));
試試這個代碼:
function countMatch(s1,s2){
var count = 0;
while(s1.length && s2.length){
if(s2.includes(s1.charAt(0))){
count++;
s2 = s2.replace(s1.charAt(0),"");
s1 = s1.slice(1);
}
else {
s1 = s1.slice(1);
}
}
return count;
}
console.log(countMatch("abcd","aad"));
//2
您可以在數組上創建自定義方法並找到所有單詞中常見的字符數。 以下步驟是在所有字符串中查找公共字符的過程列表
在Array
上創建一個原型方法,在本例中為findCommonWord
。
此方法接受一個字符串數組,因此輸入將類似於
[ "abcd", "aad","geeksforgeeksda","platdformforgeeks"].findCommonWord()
第一步是修改輸入,使用Set
從字符串中刪除重復字符,然后按字符串length
的升序對其進行sort
。 這是因為如果我們必須找到公共字符,循環次數將最少,並且必須以最小長度出現在字符串中。
然后創建一個沒有第一個字符串的新數組並拆分第一個字符串。 split
將創建一個新數組並對其進行迭代並檢查該字符是否存在於字符串的其余部分。
var s1 = "abcd", s2 = "aad", s3 = "geeksforgeeksda", s4 = "platdformforgeeks"; Array.prototype.findCommonWord = function() { let tempArray = this.map(function(item) { return [...new Set(item.split(''))].join(''); }).sort(function(a, b) { return a.length - b.length }) let count = 0; let firstElm = tempArray[0].split(''); let restElem = tempArray.splice(1); let countObject = {} for (let i = 0; i < firstElm.length; i++) { let z = findIfIncludes(restElem, firstElm[i]); if (z.length === restElem.length) { countObject[firstElm[i]] = 1; } else { countObject[firstElm[i]] = 0 } } function findIfIncludes(arr, char) { return arr.filter(item => item.includes(char)) } console.log(countObject) let totalCount = 0; for (let keys in countObject) { if (countObject[keys] > 0) { totalCount += 1; } } return totalCount; }; console.log([s1, s2, s3, s4].findCommonWord());
我使用對象來做到這一點,我有點好奇還有另一種方法,因為我也想采用算法方法,但任何有效的方法。
無論如何,這是代碼:
function commonCharacterCount(s1, s2) {
let string1Counter = {};
let string2Counter = {};
let commonCount = 0;
for(let i = 0; i < s1.length; i++){
if(!string1Counter.hasOwnProperty(s1[i])){
string1Counter[s1[i]] = 0;
}
string1Counter[s1[i]]++;
}
for(let i = 0; i < s2.length; i++){
if(!string2Counter.hasOwnProperty(s2[i])){
string2Counter[s2[i]] = 0;
}
string2Counter[s2[i]]++;
}
for(let key in string1Counter){
if(string2Counter.hasOwnProperty(key)){
if(string1Counter[key] < string2Counter[key]){
commonCount += string1Counter[key];
}
else{
commonCount += string2Counter[key];
}
}
}
return commonCount;
}
邏輯基本上只是保存每個字符串的所有字符及其計數,檢查相似性,並比較常見字符的計數。 共同字符數量較少的將是兩者共享的數量。
O(3N) 時間復雜度,O(2N) 空間復雜度(因為存儲的對象)。 我想我也可以做“刪除對象”,但在算法 IDE 上似乎是多余的,因為它不像在服務器上運行很長時間。
function commonSameCount(s1, s2) {
var s1Array = s1.split("");
var s2Array = s2.split("");
var count = 0;
let index = 0;
s1Array.filter(s1 => {
index = s2Array.findIndex(s2 => s2 == s1);
if(index >= 0){
count++;
s2Array.splice(index, 1);
}
});
return count;
}
使用正則表達式的簡單解決方案:
index.js
function getSameCount(s1,s2) {
for (let i in s2) {
s1 = s1.replace(s2[i], "1")
}
const result = s1.replace(/[^1]/g, '').length
return result
}
function numberOfSameChars(s1, s2) {
let obj = {};
let counter = 0;
for (let i=0; i<s1.length; i++){
if(s1[i] in obj) {
obj[s1[i]]++;
} else {
obj[s1[i]] = 1;
}
}
for (let i=0; i<s2.length; i++) {
if(s2[i] in obj && obj[s2[i]] > 0) {
obj[s2[i]]--;
counter++;
}
}
return counter;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.