[Swift]LeetCode722. 刪除註釋 | Remove Comments

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-wdrzebok-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!git

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★github

Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th line of the source code. This represents the result of splitting the original source code string by the newline character \n.數組

In C++, there are two types of comments, line comments, and block comments.微信

The string // denotes a line comment, which represents that it and rest of the characters to the right of it in the same line should be ignored.app

The string /* denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of */should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string /*/ does not yet end the block comment, as the ending would be overlapping the beginning.ide

The first effective comment takes precedence over others: if the string // occurs in a block comment, it is ignored. Similarly, if the string /* occurs in a line or block comment, it is also ignored.函數

If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.測試

There will be no control characters, single quote, or double quote characters. For example, source = "string s = "/* Not a comment. */";" will not be a test case. (Also, nothing else such as defines or macros will interfere with the comments.)spa

It is guaranteed that every open block comment will eventually be closed, so /* outside of a line or block comment always starts a new comment.

Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.

After removing the comments from the source code, return the source code in the same format.

Example 1:

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

The line by line code is visualized as below:
/*Test program */
int main()
{ 
  // variable declaration 
int a, b, c;
/* This is a test
   multiline  
   comment for 
   testing */
a = b + c;
}

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

The line by line code is visualized as below:
int main()
{ 
  
int a, b, c;
a = b + c;
}

Explanation: 
The string  denotes a block comment, including line 1 and lines 6-9. The string  denotes line 4 as comments./*//

Example 2:

Input: 
source = ["a/*comment", "line", "more_comment*/b"]
Output: ["ab"]
Explanation: The original source string is "a/*comment\nline\nmore_comment*/b", where we have bolded the newline characters.  After deletion, the implicit newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"].

Note:

  • The length of source is in the range [1, 100].
  • The length of source[i] is in the range [0, 80].
  • Every open block comment is eventually closed.
  • There are no single-quote, double-quote, or control characters in the source code.

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

在 C++ 中有兩種註釋風格,行內註釋和塊註釋。

字符串// 表示行註釋,表示//和其右側的其他字符應該被忽略。

字符串/* 表示一個塊註釋,它表示直到*/的下一個(非重疊)出現的全部字符都應該被忽略。(閱讀順序爲從左到右)非重疊是指,字符串/*/並無結束塊註釋,由於註釋的結尾與開頭相重疊。

第一個有效註釋優先於其餘註釋:若是字符串//出如今塊註釋中會被忽略。 一樣,若是字符串/*出如今行或塊註釋中也會被忽略。

若是一行在刪除註釋以後變爲空字符串,那麼不要輸出該行。即,答案列表中的每一個字符串都是非空的。

樣例中沒有控制字符,單引號或雙引號字符。好比,source = "string s = "/* Not a comment. */";" 不會出如今測試樣例裏。(此外,沒有其餘內容(如定義或宏)會干擾註釋。)

咱們保證每個塊註釋最終都會被閉合, 因此在行或塊註釋以外的/*老是開始新的註釋。

最後,隱式換行符能夠經過塊註釋刪除。 有關詳細信息,請參閱下面的示例。

從源代碼中刪除註釋後,須要以相同的格式返回源代碼。

示例 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].
  • 每一個塊註釋都會被閉合。
  • 給定的源碼中不會有單引號、雙引號或其餘控制字符。

Runtime: 12 ms
Memory Usage: 19.8 MB
 1 class Solution {
 2     func removeComments(_ source: [String]) -> [String] {
 3         var res:[String] = [String]()
 4         var blocked:Bool = false
 5         var out:String = String()
 6         for line in source
 7         {
 8             var i:Int = 0
 9             while(i < line.count)
10             {
11                 if !blocked
12                 {
13                     if i == line.count - 1
14                     {
15                         out.append(line[i])      
16                     }
17                     else
18                     {
19                         var t:String = line.subString(i, 2)                        
20                         if t == "/*" {
21                             blocked = true
22                             i += 1
23                         }
24                         else if t == "//" {break}
25                         else {out.append(line[i])}
26                     }
27                 }
28                 else
29                 {
30                     if i < line.count - 1
31                     {
32                         var t:String = line.subString(i, 2)
33                         if t == "*/" {
34                             blocked = false
35                             i += 1
36                         }                        
37                     }                    
38                 }
39                  i += 1
40             }
41             if !out.isEmpty && !blocked
42             {
43                 res.append(out);
44                 out = String()
45             }            
46         }
47         return res
48     }
49 }
50 
51 extension String {    
52     //subscript函數能夠檢索數組中的值
53     //直接按照索引方式截取指定索引的字符
54     subscript (_ i: Int) -> Character {
55         //讀取字符
56         get {return self[index(startIndex, offsetBy: i)]}
57     }
58     
59     // 截取字符串:指定索引和字符數
60     // - begin: 開始截取處索引
61     // - count: 截取的字符數量
62     func subString(_ begin:Int,_ count:Int) -> String {
63         let start = self.index(self.startIndex, offsetBy: max(0, begin))
64         let end = self.index(self.startIndex, offsetBy:  min(self.count, begin + count))
65         return String(self[start..<end]) 
66     }    
67 }

12ms

 1 class Solution {
 2     func removeComments(_ source: [String]) -> [String] {
 3         var res: [String] = []        
 4         var inBlock = false
 5         var resLine = ""
 6         
 7         for s in 0..<source.count {
 8             var blockEndCol = 0
 9             var ca = Array(source[s])
10             var i = 0
11             var lineComment = false
12             while i < ca.count-1 {
13                 if inBlock {
14                     if ca[i] == "*", ca[i+1] == "/" {
15                         blockEndCol = i+2
16                         i += 1
17                         inBlock = false
18                     }
19                 } else {
20                     if ca[i] == "/" {
21                         // line comment, remove the rest of the line
22                         if ca[i+1] == "/" {
23                             if i > blockEndCol {
24                                 resLine += String(ca[blockEndCol...i-1])
25                             }
26                             lineComment = true
27                             break
28                             // start of block comment
29                         } else if ca[i+1] == "*" {
30                             inBlock = true
31                             if i > blockEndCol {
32                                 resLine += String(ca[blockEndCol...i-1])
33                             }
34                             i += 1
35                         }
36                     } else {
37                     }
38                 }
39                         i += 1
40             }
41             // if we aren't in a block, add the rest of the line
42             if !inBlock && !lineComment {
43                 if ca.count > blockEndCol {
44                     resLine += String(ca[blockEndCol...ca.count-1])
45                 }
46             }
47             if !inBlock && resLine.count > 0 {
48                 res.append(resLine)
49                 resLine = ""
50             }
51         }
52         return res
53     }
54 }
相關文章
相關標籤/搜索