定的字符串str,任务是打印出给定的字符串的字典序最小的非回文置换的最后一个字符。如果不存在这样的排列,请打印“ -1” 。
例子:
Input: str = “deepqvu”
Output: v
Explanation: The string “deepquv” is the lexicographically smallest permutation which is not a palindrome.
Therefore, the last character is v.
Input: str = “zyxaaabb”
Output: z
Explanation: The string “aaabbxyz” is the lexicographically smallest permutation which is not a palindrome.
Therefore, the last character is z.
天真的方法:解决问题的最简单方法是生成给定字符串的所有可能排列,并针对每个排列检查它是否是回文。在所有获得的非回文排列中,按字典顺序打印最小的排列的最后一个字符。请按照以下步骤操作:
- 对给定的字符串str进行排序。
- 使用函数next_permutation()检查回文字符串的所有后续排列。
- 如果存在任何非回文排列,则打印其最后一个字符。
- 否则,打印“ -1”。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to check whether a string
// s is a palindrome or not
bool isPalin(string s, int N)
{
// Traverse the string
for (int i = 0; i < N; i++) {
// If unequal character
if (s[i] != s[N - i - 1]) {
return false;
}
}
return true;
}
// Function to find the smallest
// non-palindromic lexicographic
// permutation of string s
void lexicographicSmallestString(
string s, int N)
{
// Base Case
if (N == 1) {
cout << "-1";
}
// Sort the given string
sort(s.begin(), s.end());
int flag = 0;
// If the formed string is
// non palindromic
if (isPalin(s, N) == false)
flag = 1;
if (!flag) {
// Check for all permutations
while (next_permutation(s.begin(),
s.end())) {
// Check palindromic
if (isPalin(s, N) == false) {
flag = 1;
break;
}
}
}
// If non palindromic string found
// print its last character
if (flag == 1) {
int lastChar = s.size() - 1;
cout << s[lastChar] << ' ';
}
// Otherwise, print "-1"
else {
cout << "-1";
}
}
// Driver Code
int main()
{
// Given string str
string str = "deepqvu";
// Length of the string
int N = str.length();
// Function Call
lexicographicSmallestString(str, N);
return 0;
}
Java
// Java program for the
// above approach
import java.util.*;
class GFG{
// Function to check whether
// a String s is a palindrome
// or not
static boolean isPalin(String s,
int N)
{
// Traverse the String
for (int i = 0; i < N; i++)
{
// If unequal character
if (s.charAt(i) !=
s.charAt(N - i - 1))
{
return false;
}
}
return true;
}
static boolean next_permutation(char[] p)
{
for (int a = p.length - 2;
a >= 0; --a)
if (p[a] < p[a + 1])
for (int b = p.length - 1;; --b)
if (p[b] > p[a])
{
char t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1;
a < b; ++a, --b)
{
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
return false;
}
//Method to sort a string alphabetically
static String sortString(String inputString)
{
// convert input string
// to char array
char tempArray[] =
inputString.toCharArray();
// Sort tempArray
Arrays.sort(tempArray);
// Return new sorted string
return new String(tempArray);
}
// Function to find the smallest
// non-palindromic lexicographic
// permutation of String s
static void lexicographicSmallestString(String s,
int N)
{
// Base Case
if (N == 1)
{
System.out.print("-1");
}
// Sort the given String
s = sortString(s);
int flag = 0;
// If the formed String is
// non palindromic
if (isPalin(s, N) == false)
flag = 1;
if (flag != 0)
{
// Check for all permutations
while (next_permutation(s.toCharArray()))
{
// Check palindromic
if (isPalin(s, N) == false)
{
flag = 1;
break;
}
}
}
// If non palindromic String found
// print its last character
if (flag == 1)
{
int lastChar = s.length() - 1;
System.out.print(s.charAt(lastChar) + " ");
}
// Otherwise, print "-1"
else
{
System.out.print("-1");
}
}
// Driver Code
public static void main(String[] args)
{
// Given String str
String str = "deepqvu";
// Length of the String
int N = str.length();
// Function Call
lexicographicSmallestString(str, N);
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program for the
# above approach
# Function to check whether
# a String s is a palindrome
# or not
def isPalin(s, N):
# Traverse the String
for i in range(N):
# If unequal character
if (s[i] != s[N - i - 1]):
return False;
return True;
def next_permutation(p):
for a in range(len(p) - 2, 0, -1):
if (p[a] < p[a + 1]):
for b in range(len(p) - 1, -1):
if (p[b] > p[a]):
t = p[a];
p[a] = p[b];
p[b] = t;
for a in range(a + 1,
a < b,):
b = len(p) - 1;
if(a < b):
t = p[a];
p[a] = p[b];
p[b] = t;
b -= 1;
return True;
return False;
# Method to sort a string
# alphabetically
def sortString(inputString):
# convert input string
# to char array
# Sort tempArray
tempArray = ''.join(sorted(inputString));
# Return new sorted string
return tempArray;
# Function to find the smallest
# non-palindromic lexicographic
# permutation of String s
def lexicographicSmallestString(s, N):
# Base Case
if (N == 1):
print("-1");
# Sort the given String
s = sortString(s);
flag = 0;
# If the formed String is
# non palindromic
if (isPalin(s, N) == False):
flag = 1;
if (flag != 0):
# Check for all permutations
while (next_permutation(s)):
# Check palindromic
if (isPalin(s, N) == False):
flag = 1;
break;
# If non palindromic String
# found print last character
if (flag == 1):
lastChar = len(s) - 1;
print(s[lastChar],
end = "");
# Otherwise, pr"-1"
else:
print("-1");
# Driver Code
if __name__ == '__main__':
# Given String str
str = "deepqvu";
# Length of the String
N = len(str);
# Function Call
lexicographicSmallestString(str, N);
# This code is contributed by shikhasingrajput
C#
// C# program for the
// above approach
using System;
class GFG{
// Function to check whether
// a String s is a palindrome
// or not
static bool isPalin(String s,
int N)
{
// Traverse the String
for (int i = 0; i < N; i++)
{
// If unequal character
if (s[i] !=
s[N - i - 1])
{
return false;
}
}
return true;
}
static bool next_permutation(char[] p)
{
for (int a = p.Length - 2;
a >= 0; --a)
if (p[a] < p[a + 1])
for (int b = p.Length - 1;; --b)
if (p[b] > p[a])
{
char t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.Length - 1;
a < b; ++a, --b)
{
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
return false;
}
//Method to sort a string alphabetically
static String sortString(String inputString)
{
// convert input string
// to char array
char []tempArray =
inputString.ToCharArray();
// Sort tempArray
Array.Sort(tempArray);
// Return new sorted string
return new String(tempArray);
}
// Function to find the smallest
// non-palindromic lexicographic
// permutation of String s
static void lexicographicSmallestString(String s,
int N)
{
// Base Case
if (N == 1)
{
Console.Write("-1");
}
// Sort the given String
s = sortString(s);
int flag = 0;
// If the formed String is
// non palindromic
if (isPalin(s, N) == false)
flag = 1;
if (flag != 0)
{
// Check for all permutations
while (next_permutation(s.ToCharArray()))
{
// Check palindromic
if (isPalin(s, N) == false)
{
flag = 1;
break;
}
}
}
// If non palindromic String found
// print its last character
if (flag == 1)
{
int lastChar = s.Length - 1;
Console.Write(s[lastChar] + " ");
}
// Otherwise, print "-1"
else
{
Console.Write("-1");
}
}
// Driver Code
public static void Main(String[] args)
{
// Given String str
String str = "deepqvu";
// Length of the String
int N = str.Length;
// Function Call
lexicographicSmallestString(str, N);
}
}
// This code is contributed by Amit Katiyar
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the smallest non
// palindromic lexicographic string
void lexicographicSmallestString(
string s, int N)
{
// Stores the frequency of each
// character of the string s
map M;
// Traverse the string
for (char ch : s) {
M[ch]++;
}
// If there is only one element
if (M.size() == 1) {
cout << "-1";
}
// Otherwise
else {
auto it = M.rbegin();
cout << it->first;
}
}
// Driver Code
int main()
{
// Given string str
string str = "deepqvu";
// Length of the string
int N = str.length();
// Function Call
lexicographicSmallestString(str, N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG{
// Function to find the smallest non
// palindromic lexicographic string
static void lexicographicSmallestString(String s,
int N)
{
// Stores the frequency of each
// character of the string s
SortedMap M = new TreeMap();
// Converting given string to char array
char[] str = s.toCharArray();
// Traverse the string
for(char c : str)
{
if (M.containsKey(c))
{
// If char is present in M
M.put(c, M.get(c) + 1);
}
else
{
// If char is not present in M
M.put(c, 1);
}
}
// If there is only one element
if (M.size() == 1)
{
System.out.print("-1");
}
// Otherwise
else
{
System.out.print( M.lastKey() );
}
}
// Driver Code
public static void main (String[] args)
{
// Given string str
String str = "deepqvu";
// Length of the string
int N = str.length();
// Function Call
lexicographicSmallestString(str, N);
}
}
// This code is contributed by math_lover
Python3
# Python3 program for the above approach
# Function to find the smallest non
# palindromic lexicographic string
def lexicographicSmallestString(s, N):
# Stores the frequency of each
# character of the s
M = {}
# Traverse the string
for ch in s:
M[ch] = M.get(ch, 0) + 1
# If there is only one element
if len(M) == 1:
print("-1")
# Otherwise
else:
x = list(M.keys())[-2]
print(x)
# Driver Code
if __name__ == '__main__':
# Given str
str = "deepqvu"
# Length of the string
N = len(str)
# Function call
lexicographicSmallestString(str, N)
# This code is contributed by mohit kumar 29
C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find the smallest non
// palindromic lexicographic string
static void lexicographicSmallestString(String s,
int N)
{
// Stores the frequency of each
// character of the string s
SortedDictionary M = new SortedDictionary();
// Converting given string
// to char array
char[] str = s.ToCharArray();
// Traverse the string
foreach(char c in str)
{
if (M.ContainsKey(c))
{
// If char is present
// in M
M = M + 1;
}
else
{
// If char is not present
// in M
M.Add(c, 1);
}
}
// If there is only
// one element
if (M.Count == 1)
{
Console.Write("-1");
}
// Otherwise
else
{
int count = 0;
foreach(KeyValuePair m in M)
{
count++;
if(count == M.Count)
Console.Write(m.Key);
}
}
}
// Driver Code
public static void Main(String[] args)
{
// Given string str
String str = "deepqvu";
// Length of the string
int N = str.Length;
// Function Call
lexicographicSmallestString(str, N);
}
}
// This code is contributed by gauravrajput1
v
时间复杂度: O(N * N!)
辅助空间: O(1)
高效方法:为了优化上述方法,其思想是存储给定字符串str的每个字符的频率。如果所有字符都相同,则打印“ -1” 。否则,打印给定字符串str的最大字符。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the smallest non
// palindromic lexicographic string
void lexicographicSmallestString(
string s, int N)
{
// Stores the frequency of each
// character of the string s
map M;
// Traverse the string
for (char ch : s) {
M[ch]++;
}
// If there is only one element
if (M.size() == 1) {
cout << "-1";
}
// Otherwise
else {
auto it = M.rbegin();
cout << it->first;
}
}
// Driver Code
int main()
{
// Given string str
string str = "deepqvu";
// Length of the string
int N = str.length();
// Function Call
lexicographicSmallestString(str, N);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG{
// Function to find the smallest non
// palindromic lexicographic string
static void lexicographicSmallestString(String s,
int N)
{
// Stores the frequency of each
// character of the string s
SortedMap M = new TreeMap();
// Converting given string to char array
char[] str = s.toCharArray();
// Traverse the string
for(char c : str)
{
if (M.containsKey(c))
{
// If char is present in M
M.put(c, M.get(c) + 1);
}
else
{
// If char is not present in M
M.put(c, 1);
}
}
// If there is only one element
if (M.size() == 1)
{
System.out.print("-1");
}
// Otherwise
else
{
System.out.print( M.lastKey() );
}
}
// Driver Code
public static void main (String[] args)
{
// Given string str
String str = "deepqvu";
// Length of the string
int N = str.length();
// Function Call
lexicographicSmallestString(str, N);
}
}
// This code is contributed by math_lover
Python3
# Python3 program for the above approach
# Function to find the smallest non
# palindromic lexicographic string
def lexicographicSmallestString(s, N):
# Stores the frequency of each
# character of the s
M = {}
# Traverse the string
for ch in s:
M[ch] = M.get(ch, 0) + 1
# If there is only one element
if len(M) == 1:
print("-1")
# Otherwise
else:
x = list(M.keys())[-2]
print(x)
# Driver Code
if __name__ == '__main__':
# Given str
str = "deepqvu"
# Length of the string
N = len(str)
# Function call
lexicographicSmallestString(str, N)
# This code is contributed by mohit kumar 29
C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find the smallest non
// palindromic lexicographic string
static void lexicographicSmallestString(String s,
int N)
{
// Stores the frequency of each
// character of the string s
SortedDictionary M = new SortedDictionary();
// Converting given string
// to char array
char[] str = s.ToCharArray();
// Traverse the string
foreach(char c in str)
{
if (M.ContainsKey(c))
{
// If char is present
// in M
M = M + 1;
}
else
{
// If char is not present
// in M
M.Add(c, 1);
}
}
// If there is only
// one element
if (M.Count == 1)
{
Console.Write("-1");
}
// Otherwise
else
{
int count = 0;
foreach(KeyValuePair m in M)
{
count++;
if(count == M.Count)
Console.Write(m.Key);
}
}
}
// Driver Code
public static void Main(String[] args)
{
// Given string str
String str = "deepqvu";
// Length of the string
int N = str.Length;
// Function Call
lexicographicSmallestString(str, N);
}
}
// This code is contributed by gauravrajput1
v
时间复杂度: O(N)
辅助空间: O(26)