工作之余,学习了一下正则表达式,鉴于实践是检验真理的唯一标准,于是便写了一个利用正则表达式抓取百度百家文章的例子,具体过程请看下面源码:
一:获取百度百家网页内容
2 {
3 try
4 {
5 string url = "http://baijia.baidu.com/";
6 WebRequest webRequest = WebRequest.Create(url);
7 WebResponse webResponse = webRequest.GetResponse();
8 StreamReader reader = new StreamReader(webResponse.GetResponseStream());
9 string result = reader.ReadToEnd();
10 reader.Close();
11 webResponse.Close();
12 return AnalysisHtml(result);
13 }
14 catch (Exception ex)
15 {
16 throw ex;
17 }
18 }
二:通过正则表达式筛选
2 {
3 List<string[]> list = new List<string[]>();
4 string strPattern = "<h3><a\\s*.*>(?<Title>[^<]+)</a></h3>.*\\s*<p\\s*class=\"feeds-item-text\">(?<Abstract>[^<]+)<a\\s*href=\"(?<Url>.*)\"\\s*target=\"_blank\"\\s*class=\"feeds-item-more\"\\s*mon=\".*\\s*\">.*\\s*</a></p>";
5 Regex regex = new Regex(strPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant);
6 if (regex.IsMatch(htmlContent))
7 {
8 MatchCollection matchCollection = regex.Matches(htmlContent);
9 foreach (Match match in matchCollection)
10 {
11 string[] str = new string[3];
12 str[0] = match.Groups[1].Value;//获取到的是列表数据的标题
13 str[1] = match.Groups[2].Value;//获取到的是内容
14 str[2] = match.Groups[3].Value;//获取到的是链接到的地址
15 list.Add(str);
16 }
17 }
18 return list;
19 }
本文链接:C#.Net使用正则表达式抓取百度百家文章列表,转载请注明。
原题地址:https://oj.leetcode.com/problems/next-permutation/
题意:
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
解题思路:
输出字典序中的下一个排列。比如123生成的全排列是:123,132,213,231,312,321。那么321的next permutation是123。下面这种算法据说是STL中的经典算法。在当前序列中,从尾端往前寻找两个相邻升序元素,升序元素对中的前一个标记为partition。然后再从尾端寻找另一个大于partition的元素,并与partition指向的元素交换,然后将partition后的元素(不包括partition指向的元素)逆序排列。比如14532,那么升序对为45,partition指向4,由于partition之后除了5没有比4大的数,所以45交换为54,即15432,然后将partition之后的元素逆序排列,即432排列为234,则最后输出的next permutation为15234。确实很巧妙。
代码:
# @param num, a list of integer
# @return a list of integer
def nextPermutation(self, num):
if len(num) < 2: return num
partition = -1
for i in range(len(num) - 2, -1, -1):
if num < num:
partition = i
break
if partition == -1: return num[::-1]
for i in range(len(num) - 1, partition, -1):
if num > num[partition]:
num, num[partition] = num[partition], num
break
num[partition + 1:] = num[partition + 1:][::-1]
return num
参考致谢:
上述代码基于[1]进行优化
[1] http://www.cnblogs.com/zuoyuan/p/3780167.html
本文链接:[leetcode]Next Permutation @ Python,转载请注明。
没有评论:
发表评论