找到最长对称子字符串的长度

huangapple go评论69阅读模式
英文:

Find length of longest symmetric substring

问题

以下是您提供的代码的翻译部分:

public static int process(String s) {
    StringBuilder sb = new StringBuilder();
    for (char c : s.toCharArray()) {
        if (c == '<') {
            c = '<';
        } else if (c == '>') {
            c = '>';
        }
        sb.append(c);
    }
    int max = 0;
    int open = 0;
    int close = 0;
    char[] arr = sb.toString().toCharArray();
    for (int i = 0; i < arr.length; i++) {
        char c = arr[i];
        if (c == '&lt;') {
            open++;
        } else {
            int j = i;
            for (; j < arr.length && arr[j] == '&gt;'; j++) {
                close++;
                int curr = Math.min(open, close);
                max = Math.max(curr, max);
            }
            open = 0;
            close = 0;
            i = j;
        }
    }
    int curr = Math.min(open, close);
    max = Math.max(curr, max);
    return max * 2;
}

不包括代码的部分不会被翻译。希望这有助于您理解代码的功能。

英文:

I have a string of characters '<', '>', '?' for example <><??>> . Now I want to find the longest symmetric substring (first half letters are < and last half letters are >) by replacing ? with < or >

Case 1:
For example input string &lt;&gt;&lt;??&gt;&gt;, the longest can be obtained as &lt;&gt;&lt;&lt;&lt;&gt;&gt;. In this symmetric substring is <<>> which is of length 4.

Case 2:
Another example ??????, it can be replaced as &lt;&lt;&lt;&gt;&gt;&gt; with length 6.

My program:

public static int process(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (c == &#39;?&#39;) {
c = &#39;&lt;&#39;;
}
sb.append(c);
}
int max = 0;
int open = 0;
int close = 0;
char[] arr = sb.toString().toCharArray();
for (int i=0; i&lt;arr.length; i++) {
char c = arr[i];
if (c == &#39;&lt;&#39;) {
open++;
} else {
int j=i;
for(; j&lt;arr.length &amp;&amp; arr[j] == &#39;&gt;&#39;; j++) {
close++;
int curr = Math.min(open, close);
max = Math.max(curr, max);
}
open = 0;
close = 0;
i = j;
}
}
int curr = Math.min(open, close);
max = Math.max(curr, max);
return max*2;
}

My program works for case 1 and fails for case 2 as I am always replacing ? with < symbols. what is the correct approach to solve this problem.

Constraints:

Length of string can be from 1 to 200,000

答案1

得分: 1

以下是代码的翻译部分:

这是一个线性算法它有3个变量 `start`, `mid`, 和 `end`。它们都从字符串的开头开始在每一步至少有一个变量会前进而且在某个时刻我们一定能够找到任何对称模式该模式是在 `mid` 之前是 `&lt;`,然后是 `&gt;`。

请注意我在原帖中使用了对称的非典型定义具体地说前半部分的字母是 &lt;后半部分的字母是 &gt;”。这个定义与回文不同举个例子,`&lt;&lt;&gt;&lt;&lt;&gt;&gt;&lt;&gt;&gt;` 不会被视为对称

```python
def longest_symmetric(string):
    start = mid = last_gt = end = 0
    best = 0
    while start < len(string):
        #print(start, mid, last_gt, end)
        current = min(mid - start, end - mid)
        if best < current:
            best = current

        if end - mid == current and end < len(string):
            if string[end] == '?':
                end += 1
            elif string[end] == '>':
                end += 1
                last_gt = end
            else:
                end += 1
                mid = end
                start = max(start, last_gt)
        elif mid < len(string) and string[mid] == '?':
            mid += 1
        elif start < mid:
            start += 1
        else:
            start = max(start, last_gt)
            mid = mid + 1
            end = max(mid, end)

    return 2 * best

for s in ('?????', '??????', '<><<?>>', '<<?'):
    print(s, longest_symmetric(s))

请注意,这只是代码的翻译部分。如果您需要进一步的解释或讨论,请随时提出。

英文:

Here is a linear algorithm. It has 3 variables start, mid, and end. All start at the beginning of the string, at each step at least one advances, and at some point we'll be sure to find any symmetric pattern that can be made which is &lt; until mid and then &gt; afterwards.

Note, I'm using the idiosyncratic definition of "symmetric" in the OP. Namely, "first half letters are < and last half letters are >". This definition is NOT the same as a palindrome. So, for instance, &lt;&lt;&gt;&lt;&lt;&gt;&gt;&lt;&gt;&gt; would NOT be counted as symmetric.

def longest_symmetric (string):
start = mid = last_gt = end = 0
best = 0
while start &lt; len(string):
#print(start, mid, last_gt, end)
current = min(mid - start, end - mid)
if best &lt; current:
best = current
if end - mid == current and end &lt; len(string):
if string[end] == &#39;?&#39;:
end += 1
elif string[end] == &#39;&gt;&#39;:
end += 1
last_gt = end
else:
end += 1
mid = end
start = max(start, last_gt)
elif mid &lt; len(string) and string[mid] == &#39;?&#39;:
mid += 1
elif start &lt; mid:
start += 1
else:
start = max(start, last_gt)
mid = mid + 1
end = max(mid, end)
return 2*best
for s in (&#39;?????&#39;, &#39;??????&#39;, &#39;&lt;&gt;&lt;??&gt;&gt;&#39;, &#39;&lt;&lt;?&#39;):
print(s, longest_symmetric(s))

答案2

得分: 0

你没有指定输入字符串的大小,而过早优化是一切邪恶之源,我将从蛮力方法开始。我会将计算不包含?的字符串的结果的情况放到一个单独的方法中。这可以作为递归的起点。然后,对于包含?的字符串,我会简单地将其替换为<,然后递归调用自身,然后替换为>,再次递归调用自身,比较结果并看哪个更好。

请注意,这将解决问题,但随着给定输入字符串中?的数量增加,运行时间和内存都呈指数增长。如果这是一个问题,我希望您可以将这个想法作为基准,然后进行优化。

编辑:
200k绝对是指数增长的数量太多了。考虑到这一点,让我向您指出Manacher算法

它具有线性运行时间,您可能可以通过将?计为<>,以确定围绕某个中心点的最长回文字符串,将其调整到您的问题设置中。

英文:

You did not specify the size of the input Strings, and since premature optimization is the root of all evil, I would start with a brute force approach.

I would put the case of calculating the result for a "string without the letter ?" to a seperate method. This can be used as a recursion starting point.
Then, given a String that includes the letter ?, I would simply replace it with &lt; and call itself recursively, then replace it with &gt; and call itself recursively, compare the results and see which is better.

Note, that this will solve the problem, but increases exponentially in runtime as well as in memory with the number of ? letters in the given input String. If that's an issue, I hope you can take this idea as a baseline and optimize from there.

Edit:
200k is definitely too much for exponential growth. With this in mind, let me point you to Manacher's algorithm

It has linear runtime and you might be able to adjust it to your problem setting by letting count ? as both &lt; or &gt;, when determining the longest palindrome around a certain center point.

答案3

得分: 0

以下是我提出的算法;我不太确定它是否正确,但如果是正确的话,它可以在所需的约束条件下运行。

基本上,我们使用动态规划来计算从当前索引开始的输入S的最长对称子字符串(LSS),并使用其右侧邻居的结果。我相信对于任意的索引i,我们只需要关心几个状态:

  1. 如果S[i]>,那么我们不能构建从i开始的对称子字符串。
  2. 检查从i+1开始的LSS的末尾。如果它是>?,我们可以构建更长的LSS。
  3. 否则,检查是否可以保持相邻LSS的长度。我们进行一些预处理并利用所考虑的对称子字符串的对称性来快速完成这一步。
  4. 如果我们无法保持邻居的长度,则我们无法从索引i开始拥有LSS。(这是我不确定的部分

无论如何,以下是上述算法的实现以及一些Python(3+)中的测试。它通过了我想到的小测试案例,但这当然不是穷尽一切,而且我不确定算法是否正确。

def solve(S):
    """
    LSS = longest symmetric substring
    Returns (length of LSS, start index of LSS)
    """
    N = len(S)
    next_opens, closest_idx = [-1] * N, -1  # next_opens[i] = closest '(' to the left of i, inclusive
    all_qs = set()                          # index of all '?'
    for i, c in enumerate(S):
        if c == '<':
            closest_idx = i
        elif c == '?':
            all_qs.add(i)
        next_opens[i] = closest_idx

    res, F, best_idx = 0, [0] * N, -1      # F[i] = length of LSS starting from i, including it
    for i in range(N - 2, -1, -1):
        if S[i] == '>':                    # do not bother
            F[i] = 0
            continue
        nb_len = F[i + 1]
        if i+nb_len+1 < N and (S[i+nb_len+1] == '?' or S[i+nb_len+1] == '>'): # leverage symmetry of neighbor to extend
            F[i] = nb_len + 2              # +2 bc of index i and character to right
            if F[i] > res:                 # update result
                res = F[i]
                best_idx = i
        elif (S[i+nb_len-1] == '?' or S[i+nb_len-1] == '>'): # can be nb length
            n_open = nb_len//2             # how many '(' / '?' in the first half
            last_open_idx = i + n_open - 1
            if next_opens[i+nb_len-1] == last_open_idx or last_open_idx in all_qs:
                F[i] = nb_len
            else:                          # pretty sure if we can't do at least nb_len, it's 0
                F[i] = 0
        else:                              # definitely 0
            F[i] = 0

    return res, best_idx

def print_sol(S, best_len, sub_idx):
    print("--------")
    print(f"Input: {S}")
    print(f"Answer: {best_len}")
    if best_len:
        print(f"Substring: {S[sub_idx:sub_idx+best_len]} starting at index {sub_idx}")
    else:
        print("No symmetric substring found")
    return

def main():
    for S in [
        "<><??>>",
        "<>?<??>>",
        "<><<??>>",
        "<>",
        "<<<<>>>>>>",
        "??????",
        "?????",
        "?",
        "><",
        ">",
        "<",
        "<<<<???<<<<???????>>>>>>",
        "<><<>>?????><<?>",
        "??????>>"
    ]:
        res, sub_idx = solve(S)
        print_sol(S, res, sub_idx)

    return 0

if __name__ == "__main__":
    main()

以下是上述内容的一些示例输出:

--------
Input: <><??>>
Answer: 4
Substring: ??>> starting at index 3
--------
Input: <>?<??>>
Answer: 6
Substring: ?<??>> starting at index 2
--------
Input: <><<??>>
Answer: 6
Substring: <<??>> starting at index 2
--------
Input: <>
Answer: 2
Substring: <> starting at index 0
--------
Input: <<<<>>>>>>
Answer: 6
Substring: <<<<>>>>>> starting at index 0
--------
Input: ??????
Answer: 6
Substring: ?????? starting at index 0
--------
Input: ?????
Answer: 4
Substring: ???? starting at index 1
--------
Input: ?
Answer: 0
No symmetric substring found
--------
Input: ><
Answer: 0
No symmetric substring found
--------
Input: >
Answer: 0
No symmetric substring found
--------
Input: <<<<???<<<<???????>>>>>>
Answer: 18
Substring: <<<<???<<<<???????>>>>>> starting at index 1
--------
Input: <><<>>?????><<?>
Answer: 6
Substring: >>>>>> starting at index 6
--------
Input: ??????>>>>
Answer: 8
Substring: ??????>>> starting at index 0
英文:

Below is an algorithm that I came up with; I'm not too sure if it's even correct, but if it is, it runs in the required constraints.

Basically, we uses dynamic programming to calculate the Longest Symmetric Substring (LSS) of the input S from the current index, using the result from its right neighbor. I believe there are only a few states that we have to worry about, for any arbitrary index i:

  1. If S[i] is a &gt; then we can't build a symmetric substring from i.
  2. Inspect one past the end of the LSS from i+1. If it's a &gt; or ? we can make a longer LSS.
  3. Otherwise, check if we can maintain the length of the neighboring LSS. We do some preprocessing and leverage the symmetry of what's considered a symmetric substring to do this quickly.
  4. If we can't maintain the length of the neighbor, then we can't have a LSS starting from index i. (This is the part I'm not certain about)

Anyhow, below is an implementation of the above algorithm along with some tests in Python(3+). It passes the small test cases I've come up with, but this is certainly not exhaustive and I'm not sure if the algorithm is even correct.

def solve(S):
&quot;&quot;&quot;
LSS = longest symmetric substring
Returns (length of LSS, start index of LSS)
&quot;&quot;&quot;
N = len(S)
next_opens, closest_idx = [-1] * N, -1  # next_opens[i] = closest &#39;(&#39; to the left of i, inclusive
all_qs = set()                          # index of all &#39;?&#39;
for i, c in enumerate(S):
if c == &#39;&lt;&#39;:
closest_idx = i
elif c == &#39;?&#39;:
all_qs.add(i)
next_opens[i] = closest_idx
res, F, best_idx = 0, [0] * N, -1      # F[i] = length of LSS starting from i, including it
for i in range(N - 2, -1, -1):
if S[i] == &#39;&gt;&#39;:                    # do not bother
F[i] = 0
continue
nb_len = F[i + 1]
if i+nb_len+1 &lt; N and (S[i+nb_len+1] == &#39;?&#39; or S[i+nb_len+1] == &#39;&gt;&#39;): # leverage symmetry of neighbor to extend
F[i] = nb_len + 2              # +2 bc of index i and character to right
if F[i] &gt; res:                 # update result
res = F[i]
best_idx = i
elif (S[i+nb_len-1] == &#39;?&#39; or S[i+nb_len-1] == &#39;&gt;&#39;): # can be nb length
n_open = nb_len//2             # how many &#39;(&#39; / &#39;?&#39; in the first half
last_open_idx = i + n_open - 1
if next_opens[i+nb_len-1] == last_open_idx or last_open_idx in all_qs:
F[i] = nb_len
else:                          # pretty sure if we can&#39;t do at least nb_len, it&#39;s 0
F[i] = 0
else:                              # definitely 0
F[i] = 0
return res, best_idx
def print_sol(S, best_len, sub_idx):
print(&quot;--------&quot;)
print(f&quot;Input: {S}&quot;)
print(f&quot;Answer: {best_len}&quot;)
if best_len:
print(f&quot;Substring: {S[sub_idx:sub_idx+best_len]} starting at index {sub_idx}&quot;)
else:
print(&quot;No symmetric substring found&quot;)
return
def main():
for S in [
&quot;&lt;&gt;&lt;??&gt;&gt;&quot;,
&quot;&lt;&gt;?&lt;??&gt;&gt;&quot;,
&quot;&lt;&gt;&lt;&lt;??&gt;&gt;&quot;,
&quot;&lt;&gt;&quot;,
&quot;&lt;&lt;&lt;&gt;&gt;&gt;&quot;,
&quot;??????&quot;,
&quot;?????&quot;,
&quot;?&quot;,
&quot;&gt;&lt;&quot;,
&quot;&gt;&quot;,
&quot;&lt;&quot;
&quot;&lt;&lt;&lt;???&lt;???????&gt;&gt;&gt;&gt;&quot;,
&quot;&lt;&gt;&lt;&gt;?????&gt;&lt;??&gt;&quot;,
&quot;??????&gt;&gt;&quot;
]:
res, sub_idx = solve(S)
print_sol(S, res, sub_idx)
return 0
if __name__ == &quot;__main__&quot;:
main()

And below is some sample output of the above:

--------
Input: &lt;&gt;&lt;??&gt;&gt;
Answer: 4
Substring: ??&gt;&gt; starting at index 3
--------
Input: &lt;&gt;?&lt;??&gt;&gt;
Answer: 6
Substring: ?&lt;??&gt;&gt; starting at index 2
--------
Input: &lt;&gt;&lt;&lt;??&gt;&gt;
Answer: 6
Substring: &lt;&lt;??&gt;&gt; starting at index 2
--------
Input: &lt;&gt;
Answer: 2
Substring: &lt;&gt; starting at index 0
--------
Input: &lt;&lt;&lt;&gt;&gt;&gt;
Answer: 6
Substring: &lt;&lt;&lt;&gt;&gt;&gt; starting at index 0
--------
Input: ??????
Answer: 6
Substring: ?????? starting at index 0
--------
Input: ?????
Answer: 4
Substring: ???? starting at index 1
--------
Input: ?
Answer: 0
No symmetric substring found
--------
Input: &gt;&lt;
Answer: 0
No symmetric substring found
--------
Input: &gt;
Answer: 0
No symmetric substring found
--------
Input: &lt;&lt;&lt;&lt;???&lt;???????&gt;&gt;&gt;&gt;
Answer: 18
Substring: &lt;&lt;&lt;???&lt;???????&gt;&gt;&gt;&gt; starting at index 1
--------
Input: &lt;&gt;&lt;&gt;?????&gt;&lt;??&gt;
Answer: 6
Substring: ?????&gt; starting at index 4
--------
Input: ??????&gt;&gt;
Answer: 8
Substring: ??????&gt;&gt; starting at index 0

答案4

得分: 0

我在考虑这样的问题

```java
String s = "&lt;&gt;&lt;&gt;?????&gt;&lt;??&gt;";

int len = s.length();

if (len < 2) {
   return 0;
}

int[] left = new int[len - 1];
int[] right = new int[len - 1];

left[0] = s.charAt(0) != '>' ? 1 : 0;
for (int i = 1; i < len - 1; i++) {
    left[i] = s.charAt(i) != '>' ? left[i - 1] + 1 : 0;
}

right[len - 2] = s.charAt(len - 1) != '<' ? 1 : 0;
for (int i = len - 3; i >= 0; i--) {
    right[i] = s.charAt(i + 1) != '<' ? right[i + 1] + 1 : 0;
}

int max = 0;
for (int i = 0; i < len - 1; i++) {
    max = Math.max(max, 2 * Math.min(left[i], right[i]));
}

return max;
英文:

I'm thinking about something like:

String s = &quot;&lt;&gt;&lt;&gt;?????&gt;&lt;??&gt;&quot;;

int len = s.length();

if (len &lt; 2) {
   return 0;
}

int[] left = new int[len - 1];
int[] right = new int[len - 1];

left[0] = s.charAt(0) != &#39;&gt;&#39; ? 1 : 0;
for (int i = 1; i &lt; len - 1; i++) {
    left[i] = s.charAt(i) != &#39;&gt;&#39; ? left[i - 1] + 1 : 0;
}

right[len - 2] = s.charAt(len - 1) != &#39;&lt;&#39; ? 1 : 0;
for (int i = len - 3; i &gt;= 0; i--) {
    right[i] = s.charAt(i + 1) != &#39;&lt;&#39; ? right[i + 1] + 1 : 0;
}

int max = 0;
for (int i = 0; i &lt; len - 1; i++) {
    max = Math.max(max, 2 * Math.min(left[i], right[i]));
}

return max;

i.e. for each position between symbols we count the continuous length of &lt; and ? to the left and continuous length of &gt; and ? to the right.

答案5

得分: 0

public class LongestSymmetricInString {
    public static List<String> generateCombinations(String input) {
        List<String> l = new ArrayList<String>();
        char[] chars = input.toCharArray();
        generateCombinationsHelper(chars, 0, l);
        return l;
    }
    private static List<String> generateCombinationsHelper(char[] chars, int index, List<String> l) {
        if (index == chars.length) {
            l.add(new String(chars));
            System.out.println(chars);
            return l;
        }
        if (chars[index] == '?') {
            chars[index] = '<';
            generateCombinationsHelper(chars, index + 1, l);
            chars[index] = '>';
            generateCombinationsHelper(chars, index + 1, l);
            chars[index] = '?'; // 将字符重置为'?'以便回溯
        } else {
            generateCombinationsHelper(chars, index + 1, l);
        }
        return l;
    }
    public static boolean isSymmetric(String str) {
        int j = str.length();
        if(j % 2 != 0) return false;
        if(!str.startsWith("<")) return false;
        for(int i = 0; i < str.length() / 2; i++) {
            if(str.charAt(i) != '<') return false;
            if(str.charAt(str.length() - 1 - i) != '>') return false;
        }
        return true;
    }
    public static void main(String[] args) {
        // String input = "<>??>>";
        // String input = "??????";
        String input = "<<?";
        int max = 0;
        List<String> l = generateCombinations(input);
        System.out.println("**************");
        for(int i = 0; i < l.size(); i++) {
            System.out.println(l.get(i).toString());
        }
        for(String li : l) {
            for(int i = 0; i < li.length(); i++) {
                for(int j = i + 1; j < li.length(); j++) {
                    if(isSymmetric(li.substring(i, j + 1)) && max < li.substring(i, j + 1).length()) {
                        max = li.substring(i, j + 1).length();
                        System.out.println("##" + li.substring(i, j + 1) + "");
                    }
                }
            }
        }
        System.out.println(max);
    }
}
英文:
public class LongestSymmetricInString {
public static List&lt;String&gt; generateCombinations(String input) {
List&lt;String&gt; l = new ArrayList&lt;String&gt;();
char[] chars = input.toCharArray();
generateCombinationsHelper(chars, 0, l);
return l;
}
private static List&lt;String&gt; generateCombinationsHelper(char[] chars, int index, List&lt;String&gt; l) {
if (index == chars.length) {
l.add(new String(chars));
System.out.println(chars);
return l;
}
if (chars[index] == &#39;?&#39;) {
chars[index] = &#39;&lt;&#39;;
generateCombinationsHelper(chars, index + 1, l);
chars[index] = &#39;&gt;&#39;;
generateCombinationsHelper(chars, index + 1, l);
chars[index] = &#39;?&#39;; // Reset the character back to &#39;?&#39; for backtracking
} else {
generateCombinationsHelper(chars, index + 1, l);
}
return l;
}
public static boolean isSymmetric(String str) {
int j = str.length();
if(j%2 != 0) return false;
if(!str.startsWith(&quot;&lt;&quot;)) return false;
for(int i=0;i&lt;str.length()/2;i++) {
if(str.charAt(i) != &#39;&lt;&#39;) return false;
if(str.charAt(str.length()-1-i) != &#39;&gt;&#39;) return false;
}
return true;
}
public static void main(String[] args) {
//  String input = &quot;&lt;&gt;&lt;??&gt;&gt;&quot;;
//   String input = &quot;??????&quot;;
String input = &quot;&lt;&lt;?&quot;;
int max = 0;
List&lt;String&gt; l = generateCombinations(input);
System.out.println(&quot;**************&quot;);
for(int i=0;i&lt;l.size();i++){
System.out.println(l.get(i).toString());
}
for(String li : l) {
for(int i=0; i&lt;li.length();i++){
for(int j=i+1; j&lt;li.length();j++){
if(isSymmetric(li.substring(i,j+1)) &amp; max &lt; li.substring(i,j+1).length()) {
max = li.substring(i,j+1).length();
System.out.println(&quot;##&quot;+li.substring(i,j+1)+&quot;&quot;);
}
}
}
}
System.out.println(max);
}
}

答案6

得分: 0

我希望有所帮助,这是JS

function findLongestSymmetricSubstring(S) {
  let longestLength = 0;

  // 遍历S的所有可能子串
  for (let i = 0; i < S.length; i++) {
    for (let j = i + 1; j <= S.length; j++) {
      let substring = S.substring(i, j);

      // 检查子串是否对称
      if (isSymmetric(substring)) {
        let length = j - i;
        longestLength = Math.max(longestLength, length);
      }
    }
  }

  return longestLength;
}

function isSymmetric(substring) {
  let halfLength = substring.length / 2;

  // 遍历子串的前半部分
  for (let i = 0; i < halfLength; i++) {
    // 检查第二半部分中的对应字符是否处于正确的格式("&lt;"或"&gt;")或者是否为"?"字符
    if (
      (substring[i] !== "<" && substring[i] !== "?") ||
      (substring[i + halfLength] !== ">" && substring[i + halfLength] !== "?")
    ) {
      return false;
    }
  }

  return true;
}

console.log(findLongestSymmetricSubstring("<>???"));  // 输出: 4
console.log(findLongestSymmetricSubstring("??????"));  // 输出: 6

这是您提供的JavaScript代码的翻译部分。

英文:

I hope helps, is JS

function findLongestSymmetricSubstring(S) {
let longestLength = 0;
// Iterate over all possible substrings of S
for (let i = 0; i &lt; S.length; i++) {
for (let j = i + 1; j &lt;= S.length; j++) {
let substring = S.substring(i, j);
// Check if the substring is symmetric
if (isSymmetric(substring)) {
let length = j - i;
longestLength = Math.max(longestLength, length);
}
}
}
return longestLength;
}
function isSymmetric(substring) {
let halfLength = substring.length / 2;
// Iterate through the first half of the substring
for (let i = 0; i &lt; halfLength; i++) {
// Check if the corresponding characters in the second half are in the correct format (&quot;&lt;&quot; or &quot;&gt;&quot;)
// or if they are &quot;?&quot; characters
if (
(substring[i] !== &quot;&lt;&quot; &amp;&amp; substring[i] !== &quot;?&quot;) ||
(substring[i + halfLength] !== &quot;&gt;&quot; &amp;&amp; substring[i + halfLength] !== &quot;?&quot;)
) {
return false;
}
}
return true;
}
console.log(findLongestSymmetricSubstring(&quot;&lt;&gt;&lt;??&gt;&gt;&quot;));  // Output: 4
console.log(findLongestSymmetricSubstring(&quot;??????&quot;));  // Output: 6

答案7

得分: 0

public class LongestSymmetricInStringWithoutGeneration {
    public int isSymmetric(String S) {
        int max = 0;
        for(int i = 0; i < S.length(); i ++){
            for (int j = i +1; j <= S.length(); j++){
                String t = S.substring(i,j);
                if(t.length()%2 == 0){
                    int k = 0, l = t.length()-1;
                    boolean isSym = true;
                    while(k < l && isSym){
                        if(!(t.charAt(k) == '<' || t.charAt(k) == '?') && (t.charAt(l) == '>' || t.charAt(l) == '?')){
                            isSym = false;
                        }
                        k++;
                        l--;
                    }
                    if(isSym){
                        max = Math.max(max,t.length());
                    }
                }
            }
        }
        return max;
    }
}
英文:

The code in Java

public class LongestSymmetricInStringWithoutGeneration {
public int isSymmetric(String S) {
int max = 0;
for(int i = 0; i &lt; S.length(); i ++){
for (int j = i +1; j &lt;= S.length(); j++){
String t = S.substring(i,j);
if(t.length()%2 == 0){
int k = 0, l = t.length()-1;
boolean isSym = true;
while(k &lt; l &amp;&amp; isSym){
if(!(t.charAt(k) == &#39;&lt;&#39; || t.charAt(k) == &#39;?&#39;) &amp;&amp; (t.charAt(l) == &#39;&gt;&#39; || t.charAt(l) == &#39;?&#39;)){
isSym = false;
}
k++;
l--;
}
if(isSym){
max = Math.max(max,t.length());
}
}
}
}
return max;
}
}

答案8

得分: 0

以下是代码的翻译部分:

function solution(S) {
  let left = 0;
  let right = S.length - 1;
  let count = 0;
  let result = 0;

  while (left < right) {
    if (S[left] === S[right]) {
      count += S[left] === '?' ? 1 : 2;
    } else if (S[left] !== '?' && S[right] !== '?' && S[left] !== S[right]) {
      count = 0;
    } else {
      count += 2;
    }
    result = Math.max(result, count);
    left++;
    right--;
  }

  return result;
}

// Examples
console.log(solution("<>??>>")); // Output: 4
console.log(solution("??????")); // Output: 6
console.log(solution("<<?")); // Output: 2

请注意,代码中的HTML实体字符(如&lt;&gt;)已被替换为相应的字符。

英文:

Lets have some kind of tasks which expects in this manner.
We have a string made of an even number of characters ("<" and/or ">") which is called symmetric if all characters in its first half are "<" and all characters in its second half are ">". Examples of symmetric strings are: "" (empty string), "<>", "<<>>", "<<<>>>", etc.

function solution(S);
that, given a string S made of N characters (&quot;&lt;&quot;, &quot;&gt;&quot; and/or &quot;?&quot;)&quot;, returns the length of the longest symmetric substring that can be obtained after replacing question marks with &quot;&lt;&quot; or &quot;&gt;&quot; characters.
Examples:
1. For S = &quot;&lt;&gt;&lt;??&gt;&gt;&quot;, after replacing all question marks with &quot;&lt;&quot;, the string &quot;&lt;&gt;&lt;&lt;&lt;&gt;&gt;&quot; is obtained. Its longest symmetric substring is &quot;&lt;&lt;&gt;&gt;&quot;, so the function should return 4.
2. For S = &quot;??????&quot;, the optimal option is to replace the first three question marks with &quot;&lt;&quot; and the next three question marks with &quot;&gt;&quot;, thus obtaining the string &quot;&lt;&lt;&lt;&gt;&gt;&gt;&quot;. The function should return 6.
3. For S = &quot;&lt;&lt;?&quot;, the function should return 2.
HERE IS THE SOLUTION FOR THIS PROBLEM :
function solution(S) {
let left = 0;
let right = S.length - 1;
let count = 0;
let result = 0;
while (left &lt; right) {
if (S[left] === S[right]) {
count += S[left] === &#39;?&#39; ? 1 : 2;
} else if (S[left] !== &#39;?&#39; &amp;&amp; S[right] !== &#39;?&#39; &amp;&amp; S[left] !== S[right]) {
count = 0;
} else {
count += 2;
}
result = Math.max(result, count);
left++;
right--;
}
return result;
}
// Examples
console.log(solution(&quot;&lt;&gt;&lt;??&gt;&gt;&quot;)); // Output: 4
console.log(solution(&quot;??????&quot;)); // Output: 6
console.log(solution(&quot;&lt;&lt;?&quot;)); // Output: 2

huangapple
  • 本文由 发表于 2023年2月7日 02:41:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365357.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定