Finding "Longest Common Prefix" string amongst an array of strings | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public string[] strings = { "flower", "flow", "flight" };

    void Start()
    {
        Debug.Log("LCF => "+LongestCommonPrefix(strings));
    }

    public string LongestCommonPrefix(string[] strs)
    {
        if (strs == null || strs.Length == 0)
            return "";

        string prefix = strs[0];
        for (int i = 1; i < strs.Length; i++)
        {
            while(strs[i].IndexOf(prefix) != 0)
            {
                prefix = prefix.Substring(0, prefix.Length - 1);
                if (string.IsNullOrEmpty(prefix))
                    return "";
            }
        }
        return prefix;
    }
}

Adding Button in Custom Inspector | Editor Scripting | C# | Unity Game Engine


PlayerScript.cs
using UnityEngine;

public class PlayerScript : MonoBehaviour
{
    public int health = 100;
    public int maxHealth = 100;
}

PlayerScriptEditor.cs
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(PlayerScript))]
public class PlayerScriptEditor : Editor
{
    public override void OnInspectorGUI()
    {
        PlayerScript playerScript = (PlayerScript)target;
        playerScript.health = EditorGUILayout.IntField("Health", playerScript.health);
        playerScript.maxHealth = EditorGUILayout.IntField("Max-Health", playerScript.maxHealth);

        if(GUILayout.Button("Reset Values"))
        {
            playerScript.health = 100;
            playerScript.maxHealth = 100;
        }
    }
}

'Roman to Integer' Problem and its Solution | C# | Unity Game Engine


Solution.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Solution : MonoBehaviour
{
    public string s = "III";

    void Start()
    {
        Debug.Log(s + " => " + RomanToInt(s));
    }

    public int RomanToInt(string s)
    {
        var map = new Dictionary<char, int> { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 } };
        int num = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (i == 0 || map[s[i]] <= map[s[i - 1]])
            {
                num += map[s[i]];
            }
            else
            {
                num += map[s[i]] - 2 * map[s[i - 1]];
            }
        }
        return num;
    }
}