Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Parse all tags by regex pattern <\s*[a-z0-9]+
. Then sort them and print unique tags.
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collector; import java.util.stream.Collectors; public class DetectHtmlTags { private static final String TAG_PATTERN = "<\\s*[a-z0-9]+"; public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int lines = Integer.parseInt(stdin.nextLine()); Set<String> tags = new TreeSet<>(); for(int i = 0; i < lines; i++) { String line = stdin.nextLine(); Pattern pattern = Pattern.compile(TAG_PATTERN); Matcher matcher = pattern.matcher(line); while (matcher.find()) { tags.add(matcher.group().replaceAll("<", "")); } } Collector col = Collectors.joining(";"); System.out.println(tags.stream().collect(col)); stdin.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
function processData(input) { const tagPattern = /<\s*[a-z0-9]+/g var lines = input.split("\n"); var tagSet = {}; for(var i = 1; i < lines.length; i++) { var tags = lines[i].match(tagPattern); if(tags) { tags = tags.map(function(item) {return item.replace(/</, '')}); for(var j = 0; j < tags.length; j++) { tagSet[tags[j]] = true; } } } var tags = []; for(prop in tagSet) { if(tagSet.hasOwnProperty(prop)) { tags.push(prop); } } console.log(tags.sort(function (s1, s2) {return s1.localeCompare(s2)}).join(";")); } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import scala.io.Source object DetectHtmlTags extends App { private[this] val TAG_PATTERN = "<\\s*[a-z0-9]+" val lines = Source.stdin.getLines().drop(1) val tags = lines.map(parseTags).flatten.toList val tagsSet = tags.distinct.sorted println(tagsSet.mkString(";")) def parseTags(s: String): Iterator[String] = { TAG_PATTERN.r.findAllMatchIn(s).map(_.toString).map(_.replaceAll("<", "")) } } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
require "set" lines = gets.chomp.to_i tags = SortedSet.new lines.times do line = gets.chomp.downcase line.scan(/<\s*[a-z0-9]+/) do |tag| tags << tag.gsub(/</, "") end end tags_arr = tags.to_a for i in 0...tags_arr.length - 1 do print "#{tags_arr[i]};" end print "#{tags_arr[tags_arr.length - 1]}" |