Advertisement
cd62131

TagSort

Aug 1st, 2014
432
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 2.33 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. import java.util.Map;
  4. import java.util.Map.Entry;
  5. import java.util.Scanner;
  6. import java.util.TreeMap;
  7. import java.util.regex.Matcher;
  8. import java.util.regex.Pattern;
  9.  
  10. enum Tag {
  11.   タグa, タグb, タグc, タグd, タグe, タグf, タグg, タグh, タグi, タグj, タグk, タグl;
  12. }
  13.  
  14. class TagAndAux implements Comparable<TagAndAux> {
  15.   public final Tag tag;
  16.   public final String aux;
  17.  
  18.   public TagAndAux(Tag tag, String aux) {
  19.     this.tag = tag;
  20.     this.aux = aux;
  21.   }
  22.  
  23.   @Override
  24.   public int compareTo(TagAndAux o) {
  25.     if (tag.compareTo(o.tag) != 0)
  26.       return tag.compareTo(o.tag);
  27.     return aux.compareTo(o.aux);
  28.   }
  29. }
  30.  
  31. public class TagSort {
  32.   private static String tagToString(Map<TagAndAux, List<String>> block) {
  33.     StringBuilder sb = new StringBuilder();
  34.     for (Entry<TagAndAux, List<String>> e : block.entrySet())
  35.       for (String ee : e.getValue())
  36.         if (e.getKey().aux.isEmpty())
  37.           sb.append("<" + e.getKey().tag + ">" + ee + "</" + e.getKey().tag + ">\n");
  38.         else
  39.           sb.append("<" + e.getKey().tag + " " + e.getKey().aux + ">" + ee + "</" + e.getKey().tag + ">\n");
  40.     block.clear();
  41.     sb.append("\n");
  42.     return sb.toString();
  43.   }
  44.  
  45.   public static void main(String[] args) {
  46.     Scanner in = new Scanner(System.in);
  47.     Map<TagAndAux, List<String>> block = new TreeMap<TagAndAux, List<String>>();
  48.     StringBuilder sb = new StringBuilder();
  49.     Pattern re = Pattern.compile("^<(.+?)(?: (.+?))?>(.+?)</\\1>$");
  50.     while (in.hasNext()) {
  51.       String line = in.nextLine();
  52.       if (line.isEmpty()) {
  53.         sb.append(tagToString(block));
  54.       } else {
  55.         Matcher m = re.matcher(line);
  56.         if (m.find()) {
  57.           Tag t = null;
  58.           for (Tag e : Tag.values())
  59.             if (e.toString().equals(m.group(1))) {
  60.               t = e;
  61.               break;
  62.             }
  63.           String aux = m.group(2);
  64.           if (aux == null)
  65.             aux = "";
  66.           TagAndAux ta = new TagAndAux(t, aux);
  67.           if (block.get(ta) == null)
  68.             block.put(ta, new ArrayList<String>());
  69.           block.get(ta).add(m.group(3));
  70.         }
  71.       }
  72.     }
  73.     in.close();
  74.     if (!block.isEmpty()) {
  75.       sb.append(tagToString(block));
  76.     }
  77.     System.out.print(sb);
  78.   }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement