拆分解构|kmp

发布时间:2026/7/1 3:06:17

拆分解构|kmp lc214KMP 不回头重新比用前缀表跳过重复部分快速找字符串。class Solution {public:string shortestPalindrome(string s) {if (s.empty()) return ;s # string(s.rbegin(), s.rend());int n s.size();// next 数组。vectorint next(n, 0);// KMP 算法for (int i 1; i n; i) {int j next[i - 1];while (j 0 s[i]! s[j]) j next[j - 1];if (s[i] s[j]) j;next[i] j;}n / 2;return string(s.begin() n 1, s.end() - next.back()) string(s.begin(), s.begin() n);}};论自我价值认同lc273拆分为若干小于1000的数class Solution {static constexpr string ones[20] {, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten,Eleven, Twelve, Thirteen, Fourteen, Fifteen, Sixteen, Seventeen, Eighteen, Nineteen};static constexpr string tens[10] {, , Twenty, Thirty, Forty, Fifty, Sixty, Seventy, Eighty, Ninety};static constexpr string large_numbers[4] {, Thousand, Million, Billion};public:string numberToWords(int num) {if (num 0) {return Zero;}string ans;auto add [](const string s) - void {if (s.empty()) {return;}if (!ans.empty()) {ans ; // 相邻单词之间添加空格}ans s;};// 1234567811// One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Eleven// 拆分后都是小于 1000 的数 大数单位Billion/Million/Thousand/空for (int i 3; i 0; i--) {int x num / (int) pow(10, i * 3) % 1000;if (x 0) {continue;}// 百位if (x 100) {add(ones[x / 100]);add(Hundred);}// 十位和个位if (x % 100 20) { // 特殊处理小于 20 的数add(ones[x % 100]);} else {add(tens[x / 10 % 10]);add(ones[x % 10]);}add(large_numbers[i]); // 大数单位}return ans;}};

相关新闻