第二题感觉这样写虽然啰嗦了点但是好像逻辑没啥问题,为啥通过只有40%,我用的递归。有耐心的大佬帮忙指点下。
import java.util.*; import java.util.ArrayList; import java.util.Stack; public class Solution { public String solve (String str) { char[] ch=str.toCharArray(); Stack<Character> s=new Stack(); for (int i=0;i<ch.length;i++){ if (s.isEmpty()){ s.push(ch[i]); } else if (s.peek()=='0'&&ch[i]=='0'){ s.pop(); s.push('1'); }else if (s.peek()=='1'&&ch[i]=='1'){ s.pop(); }else if (s.peek()=='0'&&ch[i]=='1'){ s.push('1'); } else if (s.peek()=='1'&&ch[i]=='0'){ s.push('0'); } } ArrayList<Character> a=new ArrayList<>(); ArrayList<Character> b=new ArrayList<>(); while (!s.isEmpty()){ char m=s.pop(); a.add(m); } //System.out.println(a.size()); for (int i=a.size()-1;i>=0;i--){ b.add(a.get(i)); } String str1=b.toString(); String str2=str1.replace(",",""); String str3=str2.replace("[",""); String str4=str3.replace("]",""); String str5=str4.replace(" ",""); if (str5.equals(str)==false){ return solve(str5); } return str5; } }
全部评论
(1) 回帖