diff --git a/problems/0024.两两交换链表中的节点.md b/problems/0024.两两交换链表中的节点.md index 36f9b0cc..57034f47 100644 --- a/problems/0024.两两交换链表中的节点.md +++ b/problems/0024.两两交换链表中的节点.md @@ -459,6 +459,40 @@ impl Solution { } ``` +### C# +```C# +// 虚拟头结点 +public ListNode SwapPairs(ListNode head) +{ + var dummyHead = new ListNode(); + dummyHead.next = head; + ListNode cur = dummyHead; + while (cur.next != null && cur.next.next != null) + { + ListNode tmp1 = cur.next; + ListNode tmp2 = cur.next.next.next; + + cur.next = cur.next.next; + cur.next.next = tmp1; + cur.next.next.next = tmp2; + + cur = cur.next.next; + } + return dummyHead.next; +} +``` +``` C# +// 递归 +public ListNode SwapPairs(ListNode head) +{ + if (head == null || head.next == null) return head; + var cur = head.next; + head.next = SwapPairs(head.next.next); + cur.next = head; + return cur; +} +``` +
diff --git a/problems/0028.实现strStr.md b/problems/0028.实现strStr.md
index 629ff014..bf4ad600 100644
--- a/problems/0028.实现strStr.md
+++ b/problems/0028.实现strStr.md
@@ -1358,6 +1358,72 @@ impl Solution {
}
```
+>前缀表统一不减一
+```C#
+public int StrStr(string haystack, string needle)
+{
+ if (string.IsNullOrEmpty(needle))
+ return 0;
+
+ if (needle.Length > haystack.Length || string.IsNullOrEmpty(haystack))
+ return -1;
+
+ return KMP(haystack, needle);
+}
+
+public int KMP(string haystack, string needle)
+{
+ int[] next = GetNext(needle);
+ int i = 0, j = 0;
+ while (i < haystack.Length)
+ {
+ if (haystack[i] == needle[j])
+ {
+ i++;
+ j++;
+ }
+ if (j == needle.Length)
+ return i-j;
+ else if (i < haystack.Length && haystack[i] != needle[j])
+ if (j != 0)
+ {
+ j = next[j - 1];
+ }
+ else
+ {
+ i++;
+ }
+ }
+ return -1;
+}
+
+public int[] GetNext(string needle)
+{
+ int[] next = new int[needle.Length];
+ next[0] = 0;
+ int i = 1, j = 0;
+ while (i < needle.Length)
+ {
+ if (needle[i] == needle[j])
+ {
+ next[i++] = ++j;
+ }
+ else
+ {
+ if (j == 0)
+ {
+ next[i++] = 0;
+ }
+ else
+ {
+ j = next[j - 1];
+ }
+ }
+ }
+ return next;
+}
+```
+
diff --git a/problems/0151.翻转字符串里的单词.md b/problems/0151.翻转字符串里的单词.md
index 111c07e4..d15bb5f3 100644
--- a/problems/0151.翻转字符串里的单词.md
+++ b/problems/0151.翻转字符串里的单词.md
@@ -972,6 +972,13 @@ char * reverseWords(char * s){
}
```
+### C#
+```C# LINQ高级方法
+public string ReverseWords(string s) {
+ return string.Join(' ', s.Trim().Split(' ',StringSplitOptions.RemoveEmptyEntries).Reverse());
+}
+```
+