美文网首页
Remove Comments

Remove Comments

作者: Frank_Kivi | 来源:发表于2018-06-27 14:26 被阅读10次

https://www.lintcode.com/problem/remove-comments/description

import java.util.ArrayList;
import java.util.List;

public class Solution {
    /**
     * @param source: List[str]
     * @return: return List[str]
     */
    public List<String> removeComments(String[] source) {
        // write your code here
        List<String> list = new ArrayList<>();
        boolean block = false;
        String leftString = "";
        for (int i = 0; i < source.length; i++) {
            String s = source[i];
            if (block) {
                int i1 = s.indexOf("*/");
                if (i1 >= 0) {
                    String rightString = s.substring(i1 + 2);
                    leftString += rightString;
                    source[i] = leftString;
                    i--;
                    block = false;
                }
            } else {
                int i1 = s.indexOf("//");
                int i2 = s.indexOf("/*");
                if (i1 < 0 && i2 < 0) {
                    if (s.length() > 0) {
                        list.add(s);
                    }
                } else if (i1 < 0 || (i2 >= 0 && i2 < i1)) {
                    block = true;
                    leftString = s.substring(0, i2);
                    int i3 = s.indexOf("*/", i2 + 2);
                    if (i3 >= 0) {
                        String rightString = s.substring(i3 + 2);
                        leftString += rightString;
                        source[i] = leftString;
                        i--;
                        block = false;
                    }
                } else if (i2 < 0 || i1 < i2) {
                    String substring = s.substring(0, i1);
                    if (substring.length() > 0) {
                        list.add(substring);
                    }
                }
            }
        }
        return list;
    }
}

相关文章

网友评论

      本文标题:Remove Comments

      本文链接:https://www.haomeiwen.com/subject/cmbbyftx.html