How to check if a string can split into 4 distinct substrings in C#

2 Answers

0 votes
using System;
using System.Collections.Generic;

public class Program
{
	private static bool canSplitInto4DistinctSubstrings(string str) {
		int size = str.Length;

		if (size < 4) {
			return false;
		}

		for (int i = 1; i < size - 2; i++) {
			for (int j = i + 1; j < size - 1; j++) {
				for (int k = j + 1; k < size; k++) {
					string part1 = str.Substring(0, i);
					string part2 = str.Substring(i, j - i);
					string part3 = str.Substring(j, k - j);
					string part4 = str.Substring(k, size - k);

					if (part1.Length > 0 && part2.Length > 0 && part3.Length > 0 && part4.Length > 0) {
						HashSet<string> unique_parts = new HashSet<string>();
						unique_parts.Add(part1);
						unique_parts.Add(part2);
						unique_parts.Add(part3);
						unique_parts.Add(part4);
						if (unique_parts.Count == 4) {
							Console.WriteLine(part1 + " " + part2 + " " + part3 + " " + part4);
							return true;
						}
					}
				}
			}
		}

		return false;
	}
	public static void Main(string[] args)
	{
		string str = "AlbusDumbledore";

		if (canSplitInto4DistinctSubstrings(str)) {
			Console.Write("yes");
		}
		else {
			Console.Write("no");
		}
	}
}





/*
run:
  
A l b usDumbledore
yes
  
*/

 



answered Feb 14, 2024 by avibootz
0 votes
using System;
using System.Collections.Generic;

public class Program
{
	private static bool canSplitInto4DistinctSubstrings(string str) {
		int size = str.Length;

		if (size < 4) {
			return false;
		}

		for (int i = 2; i < size - 2; i++) {
			for (int j = i + 2; j < size - 1; j++) {
				for (int k = j + 2; k < size; k++) {
					string part1 = str.Substring(0, i);
					string part2 = str.Substring(i, j - i);
					string part3 = str.Substring(j, k - j);
					string part4 = str.Substring(k, size - k);

					if (part1.Length > 0 && part2.Length > 0 && part3.Length > 0 && part4.Length > 0) {
						HashSet<string> unique_parts = new HashSet<string>();
						unique_parts.Add(part1);
						unique_parts.Add(part2);
						unique_parts.Add(part3);
						unique_parts.Add(part4);
						if (unique_parts.Count == 4) {
							Console.WriteLine(part1 + " " + part2 + " " + part3 + " " + part4);
							return true;
						}
					}
				}
			}
		}

		return false;
	}
	public static void Main(string[] args)
	{
		string str = "AlbusDumbledore";

		if (canSplitInto4DistinctSubstrings(str)) {
			Console.Write("yes");
		}
		else {
			Console.Write("no");
		}
	}
}





/*
run:
  
Al bu sD umbledore
yes
  
*/

 



answered Feb 14, 2024 by avibootz
...