Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 转换为在交替位置具有两个不同字符的最长字符串_String_Algorithm - Fatal编程技术网

String 转换为在交替位置具有两个不同字符的最长字符串

String 转换为在交替位置具有两个不同字符的最长字符串,string,algorithm,String,Algorithm,字符串始终由两个不同的交替字符组成。例如,若字符串的两个不同字符是x和y,则t可以是XYX或yxyxy,但不能是xxyy或xyyx 通过从中删除字符,可以将某些字符串转换为字符串。从中删除字符时,必须删除其中出现的所有字符。例如,如果abaacdad删除了字符a,则字符串将变为bcdbd 给定,将其转换为尽可能长的字符串。然后在新行上打印字符串的长度;如果无法从中形成字符串,请改为打印 输入格式 第一行包含一个表示长度的整数。 第二行包含字符串 约束条件 only contains lowerc

字符串始终由两个不同的交替字符组成。例如,若字符串的两个不同字符是x和y,则t可以是XYX或yxyxy,但不能是xxyy或xyyx

通过从中删除字符,可以将某些字符串转换为字符串。从中删除字符时,必须删除其中出现的所有字符。例如,如果abaacdad删除了字符a,则字符串将变为bcdbd

给定,将其转换为尽可能长的字符串。然后在新行上打印字符串的长度;如果无法从中形成字符串,请改为打印

输入格式

第一行包含一个表示长度的整数。 第二行包含字符串

约束条件

only contains lowercase English alphabetic letters (i.e., a to z).
输出格式

打印一个整数,表示给定文件的最大长度;如果无法形成字符串,请改为打印

样本输入

十, 比菲阿布酒店

样本输出

五,

解释

中的字符是a、b、e和f。这意味着必须由其中两个字符组成

如果我们删除e和f,则得到的字符串是babab。这是有效的,因为只有两个不同的字符a和b,并且它们在字符串中交替出现

如果我们删除a和f,则得到的字符串是bebeeeb。这不是有效字符串,因为存在三个连续的e

如果我们只删除e,那么得到的字符串是babfab。这不是有效的字符串,因为它包含三个不同的字符


因此,我们打印babab的长度,这是我们的答案。

您没有提到编程语言。无论如何,这里有一个python中的蛮力解决方案-

import itertools
import re

def consecutive(string):
        if re.search(r'(.)\1', string):
            return True
        else:
            return False

n = int(input())
str = "beabeefeab"
uniq = list(set(str))
delSize = len(uniq)-2
maxLen = 0
permOfStr = itertools.permutations(uniq,delSize)
for i in permOfStr:
    temp = ''.join( c for c in str if  c not in i )
    if len(temp) > maxLen:
        if consecutive(temp) == False:
            maxLen = len(temp)
print(maxLen)

这是bruteforce的深度优先解决方案

public class Solution {

    static int max = Integer.MIN_VALUE;

    public static void main(String[] args)
    {
        int i;
        Scanner in = new Scanner(System.in);
        int len = in.nextInt();
        String s = in.next();
        List<Character> list = new ArrayList<Character>();
        for(i=0;i<s.length();i++)
        {
            if(list.indexOf(s.charAt(i))==-1) list.add(s.charAt(i));
        }
        help(s,list);
        if(max==Integer.MIN_VALUE) System.out.println(0);
        else System.out.println(max);
    }

    public static void help(String st,List<Character> list)
    {
        if(valid(st)) 
        {
            max = Math.max(max,st.length());  
            return;
        }

        int temp=list.size();   
        for(int i=0;i<temp;i++)
        {
            char ch = list.get(i);
            list.remove(i);
            help(change(st,ch),list);
            list.add(ch);
        }
    }

    public static String change(String st,char ch)
    {
        String ans = "";
        for(int i=0;i<st.length();i++)
        {
            if(st.charAt(i)!=ch) ans = ans + st.charAt(i);
        }    
        return ans;
    }

    public static boolean valid(String st)
    {
        if(st.length()==0) return false;
        if(st.length()==1) return false;

        char c1 = st.charAt(0);
        char c2 = st.charAt(1);

        if(c1==c2) return false;

        char[] ch = new char[2];
        ch[0]=c1; ch[1]=c2;

        for(int i=2;i<st.length();i++)
        {
            if(st.charAt(i)!=ch[i%2]) return false;
        }
        return true;
    }
}
在Java中:

public class Solution {

     public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int len = in.nextInt();
    String s = in.next();

    int longestSolution = 0;
    for (int i = 0; i < 26; i++)
    {
        for (int j = i + 1; j < 26; j++)
        {
            char c1 = (char)((int)'a' + i);
            char c2 = (char)((int)'a' + j);

            int currentChar = -1;
            int countChar = 0;
            for (int z = 0; z < len; z++)
            {
                if (s.charAt(z) == c1)
                {
                    if (currentChar == 1)
                    {
                        currentChar = -1;
                        break;
                    }
                    currentChar = 1;
                    countChar++;
                }
                else if (s.charAt(z) == c2)
                {
                    if (currentChar == 2)
                    {
                        currentChar = -1;
                        break;
                    }
                    currentChar = 2;
                    countChar++;
                }
            }

            if (currentChar != -1 &&
                countChar > 1 &&
                countChar > longestSolution)
            {
                longestSolution = countChar;
            }
        }
    }

    System.out.println(longestSolution);
}
}

这个解决方案已经通过了30个测试用例,并且是用C编写的。虽然这个解决方案没有经过优化,但是工作得非常完美

class Program
{
    static void Main(string[] args)
    {
        int len = Convert.ToInt32(Console.ReadLine());
        string s = Console.ReadLine();
        char[] distinct = s.Distinct().ToArray();
        var listComb =  MakeCombination(distinct);
        Console.WriteLine(MaskAndTrim(s, listComb));
    }

    /// <summary>
    /// Masking other value except comparing variable
    /// </summary>
    /// <param name="s"></param>
    /// <param name="listComb"></param>
    /// <returns></returns>
    private static int MaskAndTrim(string s, List<char[]> listComb)
    {
        int MaxLength = 0;
        List<String> validStringList = new List<string>();
        foreach (char[] item in listComb)
        {
            string newstringchar = new String(s.ToCharArray().Where(x => x == item[0] || x == item[1]).ToArray());
            string firstChar = newstringchar.Substring(0, 1);
            string secondChar = newstringchar.Substring(1, 1);
            bool validString = CheckValidString(newstringchar, firstChar, secondChar);
            if (MaxLength < newstringchar.Length && validString)
            {
                MaxLength = newstringchar.Length;
            }
        }
        return MaxLength;
    }

    /// <summary>
    /// Checking validity of string (need to come in alternate place)
    /// </summary>
    /// <param name="newstringchar"></param>
    /// <param name="firstChar"></param>
    /// <param name="secondChar"></param>
    /// <returns></returns>

    private static bool CheckValidString(string newstringchar, string firstChar, string secondChar)
    {
        //bool IsValid = false;
        for (int i = 2; i < newstringchar.Length; i++)
        {
            if (i % 2 == 0)
            {
                if (newstringchar[i] != firstChar[0]) {
                    return false;
                }

            }
            else
            {
                if (newstringchar[i] != secondChar[0])
                {
                    return false;
                }

            }
        }
        return true;
    }

    /// <summary>
    /// combination of diffrent two distinct value
    /// </summary>
    /// <param name="distinct"></param>
    /// <returns></returns>
    private static List<char[]> MakeCombination(char[] distinct)
    {
        List<char[]> charList = new List<char[]>();

        for (int i = 0; i < distinct.Length; i++)
        {
            for (int k = 0; k < distinct.Length; k++)
            {
                if (i != k)
                {
                    char[] c = new char[2];
                    c[0] = distinct[i];
                    c[1] = distinct[k];
                    charList.Add(c);
                }
            }
        }
        return charList;
    }
}

用Python优化解决方案:

def checkalter(s):
return all(s[i-1] != s[i] for i in range(1,len(s)))

def alternate(s):
    letters = set(s)
    maxLen = 0
    for pair in combinations(letters,2):
        temp = "".join(i for i in s if i in pair)
        if checkalter(temp):
            maxLen = max(maxLen, len(temp))
    return maxLen

请更准确地描述这个问题编程语言是c/c++/java