天天看點

722. 删除注釋722. 删除注釋

722. 删除注釋

給一個 C++ 程式,删除程式中的注釋。這個程式source是一個數組,其中source[i]表示第i行源碼。 這表示每行源碼由\n分隔。

在 C++ 中有兩種注釋風格,行内注釋和塊注釋。

字元串// 表示行注釋,表示//和其右側的其餘字元應該被忽略。

字元串的下一個(非重疊)出現的所有字元都應該被忽略。(閱讀順序為從左到右)非重疊是指,字元串”;” 不會出現在測試樣例裡。(此外,沒有其他内容(如定義或宏)會幹擾注釋。)

我們保證每一個塊注釋最終都會被閉合, 是以在行或塊注釋之外的/*總是開始新的注釋。

最後,隐式換行符可以通過塊注釋删除。 有關詳細資訊,請參閱下面的示例。

從源代碼中删除注釋後,需要以相同的格式傳回源代碼。

示例 1:

輸入: 
source = ["/*Test program */", "int main()", "{ ", "  // variable declaration ", "int a, b, c;", "/* This is a test", "   multiline  ", "   comment for ", "   testing */", "a = b + c;", "}"]

示例代碼可以編排成這樣:
/*Test program */
int main()
{ 
  // variable declaration 
int a, b, c;
/* This is a test
   multiline  
   comment for 
   testing */
a = b + c;
}

輸出: ["int main()","{ ","  ","int a, b, c;","a = b + c;","}"]

編排後:
int main()
{ 
  
int a, b, c;
a = b + c;
}

解釋: 
第 1 行和第 6-9 行的字元串 /* 表示塊注釋。第 4 行的字元串 // 表示行注釋。
示例 2:

輸入: 
source = ["a/*comment", "line", "more_comment*/b"]
輸出: ["ab"]
解釋: 原始的 source 字元串是 "a/*comment\nline\nmore_comment*/b", 其中我們用粗體顯示了換行符。删除注釋後,隐含的換行符被删除,留下字元串 "ab" 用換行符分隔成數組時就是 ["ab"].
注意:
           
  • source的長度範圍為[1, 100].
  • source[i]的長度範圍為[0, 80].
  • 每個塊注釋都會被閉合。
  • 給定的源碼中不會有單引号、雙引号或其他控制字元。

解題思路

  1. 處理//注釋,隻需要把改行後面的字元全部删除
  2. 當遇到,就不處理任何字元

細節:[“a/comment", “line”, "more_comment/b”] 如果出現這種情況,塊注釋會把換行也删除掉,是以我們需要把塊注釋起始行和結束行裡面的字元結合為一行

代碼

class Solution {
    public List<String> removeComments(String[] source) {
           boolean rowDel=false,mutiRowDel=false;
           
           List<String> list=new ArrayList<>();
           for(String s:source)
           {
               boolean old=mutiRowDel;
               StringBuilder sb=new StringBuilder();
               for(int i=0;i<s.length();i++)
               {
                   
                   if(i+1<s.length()&&mutiRowDel&&s.charAt(i)=='*'&&s.charAt(i+1)=='/')
                   {
                       i++;
                       mutiRowDel=false;
                       continue;
                   }
                   if(mutiRowDel) continue;
                   if(i+1<s.length()&&s.charAt(i)=='/'&&s.charAt(i+1)=='*')
                   {
                       i++;
                       mutiRowDel=true;
                       continue;
                   }   
                   if(i+1<s.length()&&s.charAt(i)=='/'&&s.charAt(i+1)=='/')
                       break;
                   sb.append(s.charAt(i));
               }

                if(sb.length()!=0)
                   {
                    if(old)
                     {
                         String t=list.remove(list.size()-1);
                         list.add(t+sb.toString());
                     }else 
                     list.add(sb.toString());    
                   }
       
           }
        return list;
    }
}