Created
April 9, 2020 07:57
-
-
Save RP-3/9029265612a4c8b9dee9e9f55bf9a442 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string[]} queries | |
* @param {string} pattern | |
* @return {boolean[]} | |
*/ | |
// O(n) but massively overcomplicated. | |
var camelMatch = function(queries, pattern) { | |
const pCapSegments = capitalSegments(pattern); | |
return queries.map((q) => { // Could have done a single pass here with two pointers ='( | |
const qCapSegments = capitalSegments(q); // ['', 'Foo', 'Bar', 'T'] || ['oo', 'Boo', 'T'] | |
if(qCapSegments.length !== pCapSegments.length) return false; // number of caps must match | |
for(let i=0; i<pCapSegments.length; i++){ // for each capital segment | |
const firstPCapChar = pCapSegments[i][0] || ''; | |
const firstQCapChar = qCapSegments[i][0] || ''; | |
if((firstPCapChar && (firstPCapChar.toUpperCase() === firstPCapChar)) || | |
(firstQCapChar && (firstQCapChar.toUpperCase() === firstQCapChar))){ // if either is capital | |
if(firstPCapChar !== firstQCapChar) return false; // the capitals must match | |
} | |
// and the remainder of the query must be a subsequence of the remainder of the pattern | |
const [a, b] = [pCapSegments[i].replace(/[A-Z]/g, ''), qCapSegments[i].replace(/[A-Z]/g, '')] | |
const sub = isSubsequence(a, b); | |
if(!sub) return false; | |
} | |
return true; | |
}); | |
function isSubsequence(a, b){ // returns true if A is a subsequence of B | |
if(a.length > b.length) return false; // subsequence cannot be longer than sequence | |
if(!a.length) return true; // empty string is always a subsequence of anything | |
let aIndex = 0; | |
for(let bIndex = 0; bIndex < b.length; bIndex++){ | |
if(b[bIndex] === a[aIndex]){ | |
aIndex++; | |
if(aIndex === a.length) return true; | |
} | |
} | |
return false; | |
} | |
function capitalSegments(str){ | |
const result = []; | |
let current = ['']; | |
for(let i=0; i<str.length; i++){ | |
if(str[i].toUpperCase() === str[i]){ | |
result.push(current.join('')); | |
current = [str[i]]; | |
}else{ | |
current.push(str[i]); | |
} | |
} | |
if(current.length) result.push(current.join('')) | |
return result; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment