当前位置: 面试刷题>> 编码和解码字符串 (经典算法题500道)


### 题目描述 **题目:编码和解码字符串** 给定一个字符串 `s`,要求你实现两个函数: 1. `encode(s)`: 将字符串 `s` 进行编码。编码规则是:遍历字符串中的每个字符,如果字符是英文字母(无论大小写),则将其替换为 `'['` 后跟字符在字母表中的位置(从 1 开始),然后跟上 `']'`。对于非字母字符,直接保留不变。 2. `decode(s)`: 将编码后的字符串 `s` 进行解码,还原成原始字符串。解码规则是:查找形如 `'[n]'` 的子串,其中 `n` 是一个数字,表示字母表中第 `n` 个字母(从 1 开始),将其替换为对应的英文字母。如果 `n` 超出字母表范围(即小于 1 或大于 26),则视为非法输入,解码时应忽略该部分。 ### 示例 - 输入:`s = "LeetCode"` - 编码后:`"L[5]e[13]tC[4]o[15]d[4]e"` - 解码后:`"LeetCode"` ### PHP 示例代码 ```php function encode($s) { $result = ''; for ($i = 0; $i < strlen($s); $i++) { $char = $s[$i]; if (ctype_alpha($char)) { $ord = ord($char) - ord('A') + 1; if (ctype_lower($char)) { $ord += 25; // Adjust for lowercase letters } $result .= '[' . $ord . ']'; } else { $result .= $char; } } return $result; } function decode($s) { $result = ''; $n = 0; for ($i = 0; $i < strlen($s); $i++) { if ($s[$i] == '[') { $n = 0; while ($s[$i+1] >= '0' && $s[$i+1] <= '9') { $n = $n * 10 + intval($s[$i+1]); $i++; } if ($n >= 1 && $n <= 26) { $result .= chr(($n - 1) % 26 + ord('A')); if ($n > 26) { // Adjust for lowercase letters $result .= chr(($n - 1) / 26 + ord('a') - 1); } } $i++; // Skip ']' } else { $result .= $s[$i]; } } return $result; } // 测试 $s = "LeetCode"; echo "Encoded: " . encode($s) . "\n"; echo "Decoded: " . decode(encode($s)) . "\n"; ``` ### Python 示例代码 ```python def encode(s): result = [] for char in s: if char.isalpha(): offset = ord(char.lower()) - ord('a') + 1 if char.isupper(): offset += 26 result.append(f'[{offset}]') else: result.append(char) return ''.join(result) def decode(s): result = [] i = 0 while i < len(s): if s[i] == '[': n = 0 i += 1 while s[i].isdigit(): n = n * 10 + int(s[i]) i += 1 if 1 <= n <= 26: if n <= 26: result.append(chr(n - 1 + ord('a'))) else: result.append(chr((n - 27) + ord('A'))) i += 1 # Skip ']' else: result.append(s[i]) i += 1 return ''.join(result) # 测试 s = "LeetCode" print("Encoded:", encode(s)) print("Decoded:", decode(encode(s))) ``` ### JavaScript 示例代码 ```javascript function encode(s) { let result = ''; for (let i = 0; i < s.length; i++) { const char = s[i]; if (/[a-zA-Z]/.test(char)) { const code = char.toLowerCase().charCodeAt(0) - 'a'.charCodeAt(0) + 1; result += '[' + (char === char.toUpperCase() ? code + 26 : code) + ']'; } else { result += char; } } return result; } function decode(s) { let result = ''; let n = 0; let parsingNumber = false; for (let i = 0; i < s.length; i++) { if (s[i] === '[') { parsingNumber = true; n = 0; } else if (parsingNumber && !isNaN(s[i])) { n = n * 10 + parseInt(s[i]); } else if (parsingNumber && s[i] === ']') { if (n >= 1 && n <= 26) { result += String.fromCharCode(n <= 26 ? n + 'a'.charCodeAt(0) - 1 : n - 26 + 'A'.charCodeAt(0) - 1); } parsingNumber = false; } else { if (!parsingNumber) { result += s[i]; } } } return result; } // 测试 const s = "LeetCode"; console.log("Encoded:", encode(s)); console.log("Decoded:", decode(encode(s))); ``` ### 额外提示 码小课网站中有更多相关内容分享给大家学习,包括但不限于算法题解、编程技巧、数据结构等,欢迎访问码小课网站进行深入学习。
推荐面试题