d574: 節約符咒

題目:http://zerojudge.tw/ShowProblem
程式碼:

import java.util.Scanner;
public class d574 {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Scanner sc = new Scanner(System.in);
  while(sc.hasNext()){
   int i,c =1;
   String s = sc.next();
   String s1 = sc.next();
   StringBuilder ans = new StringBuilder();
   for(i=0;i<s1.length()-1;i++){
    if(s1.charAt(i)==s1.charAt(i+1)){
     c++;
     
    }else if(s1.charAt(i)!=s1.charAt(i+1)){
     ans.append(c);
     if(s1.charAt(i)!=s1.charAt(i+1)){
      ans.append(s1.charAt(i));
     }
     c=1;
     continue;
    }
   }
   ans.append(c+""+s1.charAt(i));
   if((s1.length()<ans.length())||(s1.length()==ans.length())){
    System.out.print(s1);
   }else{
    System.out.print(ans);
   }
  }
  
 }

}
感謝學長小提示~~

留言

熱門文章