寻找相同子串

寻找相同子串

 1process.stdin.resume();  2process.stdin.setEncoding('utf-8');  3let input = '';  4  5process.stdin.on('data', (data) => {  6 input += data;  7});  8  9process.stdin.on('end', () => { 10 let inputArray = input.split('\n'); 11 const t = inputArray[0]; 12 const p = inputArray[1]; 13 14 /** 15 * 查找子串在字符串中第一次出现的位置(基于 1 的索引) 16 * @param {string} t - 主字符串 17 * @param {string} p - 要查找的子串 18 * @returns {string|number} - 子串第一个字符在主字符串中的下标或"No" 19 */ 20 function findSubstringIndex(t, p) { 21 const tLength = t.length; 22 const pLength = p.length; 23 24 if (pLength === 0) { 25 return 0; // 如果p为空字符串,根据题意应返回0或视为无效输入,但题目未明确说明,这里简单处理为返回0(实际中可能需要根据具体需求调整) 26 } 27 28 if (tLength < pLength) { 29 return "No"; // t比p短,不可能包含p 30 } 31 32 for (let i = 0; i <= tLength - pLength; i++) { 33 if (t.substr(i, pLength) === p) { 34 return i + 1; // 返回基于1的索引 35 } 36 } 37 38 return "No"; // 未找到匹配的子串 39 } 40 41 const result = findSubstringIndex(t, p); 42 console.log(result); 43 44 process.exit(); 45});
process.stdin.resume(); process.stdin.setEncoding('utf-8'); let input = ''; process.stdin.on('data', (data) => { input += data; }); process.stdin.on('end', () => { let inputArray = input.split('\n'); const t = inputArray[0]; const p = inputArray[1]; /** * 查找子串在字符串中第一次出现的位置(基于 1 的索引) * @param {string} t - 主字符串 * @param {string} p - 要查找的子串 * @returns {string|number} - 子串第一个字符在主字符串中的下标或"No" */ function findSubstringIndex(t, p) { const tLength = t.length; const pLength = p.length; if (pLength === 0) { return 0; // 如果p为空字符串,根据题意应返回0或视为无效输入,但题目未明确说明,这里简单处理为返回0(实际中可能需要根据具体需求调整) } if (tLength < pLength) { return "No"; // t比p短,不可能包含p } for (let i = 0; i <= tLength - pLength; i++) { if (t.substr(i, pLength) === p) { return i + 1; // 返回基于1的索引 } } return "No"; // 未找到匹配的子串 } const result = findSubstringIndex(t, p); console.log(result); process.exit(); });

Powered By 可尔物语

浙ICP备11005866号-12