题目1. 通过键盘输入一串小写字母(a~z)组成的字符串。请编写一个字符串压缩程序,将字符串中连续出现的重复字母进行压缩,并输出压缩后的字符串。
压缩规则:
(1)仅压缩连续重复出现的字符。比如字符串"abcbc"由于无连续重复字符,压缩后的字符串还是"abcbc"。
(2)压缩字段的格式为"字符重复的次数+字符"。例如:字符串"xxxyyyyyyz"压缩后就成为"3x6yz"。
要求实现函数:
void stringZip(const char *pInputStr, long lInputLen, char *pOutputStr);
输入pInputStr: 输入字符串lInputLen: 输入字符串长度
输出 pOutputStr: 输出字符串,空间已经开辟好,与输入字符串等长;
注意:只需要完成该函数功能算法,中间不需要有任何IO的输入输出
示例
输入:“cccddecc” 输出:“3c2de2c”
输入:“adef” 输出:“adef”
输入:“pppppppp” 输出:“8p”
String stringZip(String input) {
if (input != null) {
char[] chars = input.toCharArray();
char[] outChars = new char[chars.length];
int pos = 0;
for (int i = 0; i < chars.length;) {
char cur = char[i];
count = 1;
int j = i + 1;
for (; j < chars.length; j++) {
if (chars[j] == cur) {
count++;
} else {
break;
}
}
if (count > 1) {
String value = String.valueOf(count);
for (int k = 0; k < value.length(); k++) {
outChars[pos++] = value.charAt(k);
}
}
outChars[pos++] = cur;
i = j;
}
return String.valueOf(outChars, 0, pos);
}
}
题目2:子串匹配母串,如果匹配,输出子串匹配的起始位置,否则输出-1。?可以代表一个字符,*代表一个或者多个。从键盘输入,先输入子串,再输入母串。子串母串长度均小于20。运行时间和内存无限制。
因为有通配符,无法用KMP算法,只能暴力匹配
public int find(String source, String target) {
if (source == null || source.length() == 0 || target == null || target.length() == 0 || source.length() < target.length()) {
return -1;
}
for (int i = 0; i < source.length(); i++) {
int j = i
for (; j < source.length() && j - i < target.length(); j++) {
if (target[j-i] == “?”) {
continue;
} else if (target[j-i] == “*”) {
if (j - i + 1 < target.length() && j+1 < source.length()) {
return find(source.subString(j+1, source.length),
target.subString(j -i + 1; target.length()));
} else if (j - i + 1 == target.length()) {
return i;
} else if {
return -1;
}
} else {
if (source[j] == target[j-i]) {
continue;
} else {
break;
}
}
}
if (j-i == target.length()) {
return i;
}
}
return -1;
}