找到最大的偶数整数,它是 S 的非空子串
给定一个大小为N的字符串S ,表示一个大整数。任务是找到最大的偶数整数,它是一个非空子字符串 的S。如果不能生成偶数,则返回一个空字符串。
例子:
Input: S = “4206”
Output: “4206”
Explanation: “4206” is already an even number.
Input: S = “23”
Output: “2”
Explanation: “The only non-empty substrings are “2”, “3”, and “23”. “2” is the only even number.
Input: S = “17”
Output: “”
Explanation: There is no even valued substring in the given string
方法:可以通过从右边找到第一个偶数字符来解决该任务,假设它在索引' idx '处找到。
生成的最大偶数非空子字符串将是[0, idx]范围内 S 的子字符串。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the largest even valued
// substring
void get(string& s)
{
int N = s.length();
int idx = -1;
// Finding the rightmost even character
for (int i = N - 1; i >= 0; i--) {
if ((s[i] - '0') % 2 == 0) {
idx = i;
break;
}
}
if (idx == -1)
cout << "";
else
cout << s.substr(0, idx + 1);
}
// Driver Code
int main()
{
string S = "4206";
get(S);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
// Function to find the largest even valued
// substring
static void get(String s)
{
int N = s.length();
int idx = -1;
// Finding the rightmost even character
for (int i = N - 1; i >= 0; i--) {
if ((s.charAt(i) - '0') % 2 == 0) {
idx = i;
break;
}
}
if (idx == -1)
System.out.print("");
else
System.out.print(s.substring(0, idx + 1));
}
// Driver Code
public static void main (String[] args) {
String S = "4206";
get(S);
}
}
// This code is contributed by hrithikgarg03188.
Python3
# Python code for the above approach
# Function to find the largest even valued
# substring
def get(s):
N = len(s);
idx = -1;
# Finding the rightmost even character
for i in range(N - 1, 0, -1):
if ((ord(s[i]) - ord('0')) % 2 == 0):
idx = i;
break;
if (idx == -1):
print("");
else:
print(s[0: idx + 1]);
# Driver Code
S = "4206";
get(S);
# This code is contributed by gfgking
C#
// C# program for the above approach
using System;
class GFG {
// Function to find the largest even valued
// substring
static void get(string s)
{
int N = s.Length;
int idx = -1;
// Finding the rightmost even character
for (int i = N - 1; i >= 0; i--) {
if ((s[i] - '0') % 2 == 0) {
idx = i;
break;
}
}
if (idx == -1)
Console.Write("");
else
Console.Write(s.Substring(0, idx + 1));
}
// Driver Code
public static void Main () {
string S = "4206";
get(S);
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
4206
时间复杂度: O(N)
辅助空间: O(1)