Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace substring
- {
- public class Main
- {
- private int[,] matrix;
- private List<string> substrings;
- private List<Position> pos;
- public List<string> GetSubstring(string v1, string v2)
- {
- if (v1 == null || v2 == null) throw new ArgumentException();
- if (v1.Length == 0 || v2.Length == 0) return new List<string>();
- else if (v1.Equals(v2)) return new List<string>() { v1 };
- v1 = " " + v1;
- v2 = " " + v2;
- pos = new List<Position>();
- substrings = new List<string>();
- matrix = new int[v1.Length, v2.Length];
- MatrixComplete(v1, v2);
- Stringer(v1);
- return substrings;
- }
- private void MatrixComplete(string v1, string v2)
- {
- var max = 0;
- for (int i = 0; i < v1.Length; i++)
- {
- for (int j = 0; j < v2.Length; j++)
- {
- if (i == 0 || j == 0) continue;
- if (v1[i] == v2[j])
- {
- if (matrix[i - 1, j - 1] == 0) matrix[i, j] = 1;
- else matrix[i, j] = matrix[i - 1, j - 1] + 1;
- if (max < matrix[i, j])
- {
- max = matrix[i, j];
- pos.Clear();
- pos.Add(new Position(i, j, max));
- }
- else if (max == matrix[i, j]) pos.Add(new Position(i, j, max));
- }
- }
- }
- }
- private void Stringer(string v1)
- {
- var substring = new StringBuilder();
- for (int i = 0; i < pos.Count; i++)
- {
- for (int j = pos[i].Lenght - 1; j > -1; j--) substring.Append(v1[pos[i].X - j]);
- substrings.Add(substring.ToString());
- substring.Clear();
- }
- }
- }
- public class Position
- {
- public int X { get; }
- public int Y { get; }
- public int Lenght { get; }
- public Position(int x, int y, int lenght)
- {
- X = x;
- Y = y;
- Lenght = lenght;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment