LeetCode1410。HTMLエンティティパーサー(ハッシュマップ)

1.タイトル

「HTMLエンティティパーサー」は、HTMLコードを入力として受け取り、これらすべての特殊文字エンティティを文字自体に置き換える特殊なパーサーです。

これらの特殊文字と対応するHTMLの文字エンティティには、次のものがあります。

双引号:字符实体为 " ,对应的字符是 " 。
单引号:字符实体为 ' ,对应的字符是 ' 。
与符号:字符实体为 & ,对应对的字符是 &
大于号:字符实体为 > ,对应的字符是 >
小于号:字符实体为 &lt; ,对应的字符是 <
斜线号:字符实体为 &frasl; ,对应的字符是 /

文字列テキストを入力し、HTMLエンティティパーサーを実装して、パーサーの解析結果を返します。

示例 1
输入:text = "&amp; is an HTML entity but &ambassador; is not."
输出:"& is an HTML entity but &ambassador; is not."
解释:解析器把字符实体 &amp;& 替换

示例 2
输入:text = "and I quote: &quot;...&quot;"
输出:"and I quote: \"...\""

示例 3
输入:text = "Stay home! Practice on Leetcode :)"
输出:"Stay home! Practice on Leetcode :)"

示例 4
输入:text = "x &gt; y &amp;&amp; x &lt; y is always false"
输出:"x > y && x < y is always false"

示例 5
输入:text = "leetcode.com&frasl;problemset&frasl;all"
输出:"leetcode.com/problemset/all"
 
提示:
1 <= text.length <= 10^5
字符串可能包含 256 个ASCII 字符中的任意字符。

ソース:LeetCode
リンク:https ://leetcode-cn.com/problems/html-entity-parser
著作権は控除ネットワークに属しています。商用転載の正式な許可書に連絡し、非商用転載の出典を明記してください。

2.問題解決

  • テキストをトラバース&し、最初に累積文字;、最後に累積文字を見つけ、その単語がハッシュテーブルにあるかどうかを確認するか、置換します
class Solution {
public:
    string entityParser(string text) {
    	unordered_map<string,string> m = {{"&quot;","\""},{"&apos;","'"},{"&amp;","&"},
    		{"&gt;",">"},{"&lt;","<"},{"&frasl;","/"}};
    	string word;
    	string ans;
    	for(int i = 0; i < text.size(); ++i)
    	{
    		if(text[i] != '&')
    			ans += text[i];
    		else
    		{
    			word = "";
    			while(i < text.size())
    			{
    				word += text[i];
    				if(text[i]==';')
    					break;
    				i++;
    			}
    			if(m.count(word))
    				ans += m[word];
    			else
    				ans += word;
    		}
    	}
    	return ans;
    }
};

288 ms 19.2 MB

元の記事839件を公開 2083 年に賞賛 44万回の閲覧+

おすすめ

転載: blog.csdn.net/qq_21201267/article/details/105478099