Pergunta de entrevista da empresa Meta

String manipulation: Giving a string input, containing comments, implement a method to output the given string excluding the comments.

Respostas da entrevista

Sigiloso

14 de fev. de 2015

comments_dfa = ( ({ '/': 1, 'oth': 0, 'in_comment': False, }, { '/': 2, '*': 3, 'oth': 0, 'in_comment': False, }, { '\n': 0, 'oth': 2, 'in_comment': True, }, { '*': 4, 'oth': 3, 'in_comment': True, }, { '/': 0, 'oth': 3, 'in_comment': True, }) ) def remove_comments(input_string): result = '' cs = 0 comment_status = False for c in input_string: if not comments_dfa[cs]['in_comment'] or c == '\n': result += c if comments_dfa[cs]['in_comment'] and not comment_status: result = result[:-2] comment_status = comments_dfa[cs]['in_comment'] if c in comments_dfa[cs]: cs = comments_dfa[cs][c] else: cs = comments_dfa[cs]['oth'] return result print remove_comments(""" This is a /* test */ and / I want to check // what happends here 123 /* Is this system */ working? or not??? // Testing new line """)

Sigiloso

15 de fev. de 2015

public class RemoveCommentFromString { public enum State { OutsideComment, InsideLineComment, InsideBlockComment, InsideBlockCommentNoNewLineYet } public static String removeComments(String str) { State state = State.OutsideComment; StringBuilder endResult = new StringBuilder(); Scanner s = new Scanner(str); s.useDelimiter(""); while (s.hasNext()) { String c = s.next(); switch (state) { case OutsideComment: if (c.equals("/") && s.hasNext()) { String c2 = s.next(); if (c2.equals("/")) { state = State.InsideLineComment; } else if (c2.equals("*")) { state = State.InsideBlockCommentNoNewLineYet; } else { endResult.append(c).append(c2); } } else { endResult.append(c); } break; case InsideLineComment: if (c.equals("\n")) { endResult.append("\n"); state = State.OutsideComment; } break; case InsideBlockCommentNoNewLineYet: if (c.equals("\n")) { endResult.append("\n"); state = State.InsideBlockComment; } break; case InsideBlockComment: if (c.equals("*") && s.hasNext()) { String c2 = s.next(); if (c2.equals("/")) { state = State.OutsideComment; } } break; } } return endResult.toString(); } public static void main(String[] args) { String str = "start_code();// first comment\n" + "more_code(); /* block comment\n" + "second line of block comment */\n" + "more_code_after_block();"; System.out.println("Scanner: " + removeComments(str)); } }