【问题描述】 编写一函数expand(s1,s2),用以将字符串s1中的缩记符号在字符串s2中扩展为等价的完整字符,例如将a-d扩展为abcd。该函数可以处理大小写字母和数字,并可以处理a-b-c、a-z0-9与-a-z等类似的情况。在main函数中测试该函数:从键盘输入包含缩记符号的字符串,然后调用该函数进行扩展,输出扩展结果。 注意: 待扩展字符串中有可能包含空格,例如:a-d x-z应扩展成:abcd xyz。所以读入待扩展字符串时,应能够读入包含空格的字符串。 只要缩记符号-之后的字符比之前的字符的ASCII码值大,就要将它们之间的所有字符扩展出来,例如:Z-a之间的字符也要扩展出来; 特殊情况:a-b-c将被扩展为:abc。a-a将被扩展为:a-a。 【输入形式】 从键盘输入包含扩展符的字符串 【输出形式】 输出扩展后的字符串 【输入样例】 a-c-u-B 【输出样例】 abcdefghijklmnopqrstu-B
时间: 2023-06-14 14:04:10 浏览: 98
```python
def expand(s1, s2):
i = 0
while i < len(s1):
if s1[i] == '-' and i > 0 and i < len(s1) - 1:
pre = s1[i-1]
nxt = s1[i+1]
if pre.isalnum() and nxt.isalnum() and nxt > pre:
for c in range(ord(pre)+1, ord(nxt)):
s2.append(chr(c))
elif pre == nxt:
s2.append(pre)
i += 1
else:
s2.append(s1[i])
i += 1
s1 = input().strip()
s2 = []
expand(s1, s2)
print(''.join(s2))
```
相关问题
JAVA编写一个函数longestPalindrome(),找到非空字符串s中最长回文子串
以下是JAVA编写的longestPalindrome()函数代码:
```
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) {
return "";
}
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
private int expandAroundCenter(String s, int left, int right) {
int L = left, R = right;
while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
L--;
R++;
}
return R - L - 1;
}
```
该函数使用中心扩展算法,首先判断字符串是否为空,然后遍历字符串中的每个字符,分别以当前字符为中心向左右扩展,找到最长回文子串的长度。在遍历过程中更新最长回文子串的起始位置和结束位置,最后返回最长回文子串。expandAroundCenter()函数用于以当前字符为中心向左右扩展并返回最长回文子串的长度。
用Java给定一个字符串,输出字符串中的最长回文字符串
好的,下面是一个基于 Java 的中心扩展法实现的代码示例:
```java
public static String longestPalindrome(String s) {
if (s == null || s.length() < 1) {
return "";
}
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
private static int expandAroundCenter(String s, int left, int right) {
int L = left, R = right;
while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
L--;
R++;
}
return R - L - 1;
}
```
这个函数的输入是一个字符串,输出是该字符串中最长的回文子串。其中 `expandAroundCenter` 函数用于以某个字符为中心扩展回文串,`longestPalindrome` 函数遍历字符串中的每个字符,以该字符为中心扩展回文串并记录最长的回文串。最后返回最长回文串的子字符串即可。
希望这个代码对您有所帮助。