手写代码:驼峰字符串问题,给定一个驼峰样式的字符串例如“AaABbBcBbcvQv........”->“bc”,两个一样的字符夹着一个不一样的字符, 处理这个字符串去掉所有的驼峰。
#非递归方式
def tuofeng(self,str):
if not str:return ""
list1 = list(str)
n = len(list1)
if n == 1 or n == 2:return list1
index = 0
while index + 2 < n:
start = 0
end = 0
if list1[index] == list1[index+2] and list1[index] != list1[index+1]:
start = index
end = index + 2
if end + 2 < n:
while list1[end] == list1[end+2] and list1[end] != list1[end+1]:
end = end + 2
if end >= n:
break;
del list1[start:end + 1]
index = 0
n = len(list1)
else:
index = index + 1
return ''.join(list1) def getRes(st):
li = list(st)
n = len(li)
left = 0
if n <= 2:
return st
while left + 2 <= n-1:
if li[left] == li[left+2] and li[left] != li[left+1]:
li.pop(left)
n -= 1
# 避免pop删除驼峰首字符后,驼峰前面的字符再次出现驼峰
if left >= 2:
left -= 2
elif left == 1:
left -= 1
else:
left += 1
return "".join(li)
if __name__ == "__main__":
res = getRes("akasdsadawasfsi")
print(res) # 结果: kasdwafsi 2020/10/19 字节跳动二面
非递归解法,用栈保存可能不是驼峰的字符,如果遇到驼峰就将前a个pop
import java.util.LinkedList;
public class Solution {
String eliminatingHump(String s){
StringBuilder ans=new StringBuilder();
char pre;
LinkedList<Character> rec=new LinkedList<>();
rec.add(s.charAt(0));
rec.add(s.charAt(1));
int a=2;
for(int i=2;i<s.length();i++){
pre=s.charAt(i-2);
if(s.charAt(i)!=pre){
rec.add(s.charAt(i));
a++;
}
else{
if(a>2){
a=2;
}
while(a>0){
rec.remove(rec.size()-1);
a--;
}
}
}
for(int i=0;i<rec.size();i++){
ans.append(rec.get(i));
}
return ans.toString();
}
public static void main(String args[]){
String ans=new Solution().eliminatingHump("AaABbBcBbcvQvaaaaaaaaaaaaaa");
System.out.print(ans);
}
}
s = input() def func(s): res = '' i = 0 while i< len(s): pre = s[i] mark = True j = i+2 while j< len(s): next = s[j] mid = s[j-1] if pre==next and pre != mid: i = j mark = False else: break j += 2 if mark: res += pre i += 1 if len(s) == len(res): return res else: return func(res) print(func(s))根据上述大佬修改。