classSolution: defsplitMessage(self, message: str, limit: int) -> List[str]: i = cap = 0 whileTrue: i += 1 if i < 10: tail_len = 5# 结尾的长度 elif i < 100: if i == 10: cap -= 9# 前面的结尾的长度都 +1,那么容量就要减小 tail_len = 7 elif i < 1000: if i == 100: cap -= 99 tail_len = 9 else: if i == 1000: cap -= 999 tail_len = 11 if tail_len >= limit: return [] # cap 无法增大,寄 cap += limit - tail_len if cap < len(message): continue# 容量没有达到,继续枚举
ans, k = [], 0 for j inrange(1, i + 1): tail = f"<{j}/{i}>" if j == i: ans.append(message[k:] + tail) else: m = limit - len(tail) ans.append(message[k: k + m] + tail) k += m return ans
classSolution { public String[] splitMessage(String message, int limit) { varn= message.length(); for (inti=1, cap = 0, tail_len; ; ++i) { if (i < 10) tail_len = 5; // 结尾的长度 elseif (i < 100) { if (i == 10) cap -= 9; // 前面的结尾的长度都 +1,那么容量就要减小 tail_len = 7; } elseif (i < 1000) { if (i == 100) cap -= 99; tail_len = 9; } else { if (i == 1000) cap -= 999; tail_len = 11; } if (tail_len >= limit) returnnewString[]{}; // cap 无法增大,寄 cap += limit - tail_len; if (cap < n) continue; // 容量没有达到,继续枚举
varans=newString[i]; for (intj=0, k = 0; j < i; ++j) { vartail="<" + (j + 1) + "/" + i + ">"; if (j == i - 1) ans[j] = message.substring(k) + tail; else { varm= limit - tail.length(); ans[j] = message.substring(k, k + m) + tail; k += m; } } return ans; } } }
classSolution { public: vector<string> splitMessage(string message, int limit){ int n = message.length(); for (int i = 1, cap = 0, tail_len;; ++i) { if (i < 10) tail_len = 5; // 结尾的长度 elseif (i < 100) { if (i == 10) cap -= 9; // 前面的结尾的长度都 +1,那么容量就要减小 tail_len = 7; } elseif (i < 1000) { if (i == 100) cap -= 99; tail_len = 9; } else { if (i == 1000) cap -= 999; tail_len = 11; } if (tail_len >= limit) return {}; // cap 无法增大,寄 cap += limit - tail_len; if (cap < n) continue; // 容量没有达到,继续枚举
vector<string> ans(i); for (int j = 0, k = 0; j < i; ++j) { string tail = "<" + to_string(j + 1) + "/" + to_string(i) + ">"; if (j == i - 1) ans[j] = message.substr(k) + tail; else { int m = limit - tail.length(); ans[j] = message.substr(k, m) + tail; k += m; } } return ans; } } };