String 难以理解的技术面试
这是最近一次节目采访中提出的一个问题 给定一个字符串“str”和一对“N”交换索引,生成一个按字典顺序排列的最大字符串。交换索引可以重复使用任意次数 例如: 答复:String 难以理解的技术面试,string,String,这是最近一次节目采访中提出的一个问题 给定一个字符串“str”和一对“N”交换索引,生成一个按字典顺序排列的最大字符串。交换索引可以重复使用任意次数 例如: 答复: cdba, cbad, dbac,dbca 您应该只打印“dbca”,它是字典中最大的 这听起来可能很幼稚,但我完全没有理解这个问题。有人能帮我理解这个问题的意思吗?我想这是说,给定字符串mystring=“abdc”,您会被指示在指定的索引对处切换字符,以便生成按字典顺序排列的“最大”字符串(也就是说,如果你把所有可能的字符串
cdba, cbad, dbac,dbca
您应该只打印“dbca”,它是字典中最大的
这听起来可能很幼稚,但我完全没有理解这个问题。有人能帮我理解这个问题的意思吗?我想这是说,给定字符串
mystring=“abdc”
,您会被指示在指定的索引对处切换字符,以便生成按字典顺序排列的“最大”字符串(也就是说,如果你把所有可能的字符串都放在最后一个索引中,它就会结束。)因此你有两个有效的操作:(1)将mystring[1]
与mystring[4]
(“abdc”
-->“cbda”
)和(2)将mystring[3]
与mystring[4]
(“abdc”
-->)。此外,您还可以将链操作相乘:操作(1)后跟(2)(“abdc”
-->“cbda”
-->“cbad”
),反之亦然(“abdc”
“abcd”
“dbca”),等等(“abdc”
>“cbda”
)))
然后对这些进行(反向)排序,并弹出顶部索引:
>>> allPermutations = ['abcd', 'cbad', 'abdc', 'cbda', 'dbca', 'dbac']
>>> lexSorted = sorted(allPermutations, reverse=True) # ['dbca', 'dbac', 'cbda', 'cbad', 'abdc', 'abcd']
>>> lexSorted.pop(0)
'dbca'
根据@ncemami的澄清,我提出了这个解决方案
public static String swap(String str, Pair<Integer, Integer> p1, Pair<Integer, Integer> p2){
TreeSet<String> set = new TreeSet<>();
String s1 = swap(str, p1.getKey(), p1.getValue());
set.add(s1);
String s2 = swap(s1, p2.getKey(), p2.getValue());
set.add(s2);
String s3 = swap(str, p2.getKey(), p2.getValue());
set.add(s3);
String s4 = swap(s3, p1.getKey(), p1.getValue());
set.add(s4);
return set.last();
}
private static String swap(String str, int a, int b){
StringBuilder sb = new StringBuilder(str);
char temp1 = str.charAt(a);
char temp2 = str.charAt(b);
sb.setCharAt(a, temp2);
sb.setCharAt(b, temp1);
return sb.toString();
}
公共静态字符串交换(字符串str,对p1,对p2){
树集=新树集();
字符串s1=swap(str,p1.getKey(),p1.getValue());
添加(s1);
字符串s2=swap(s1,p2.getKey(),p2.getValue());
增加(s2);
字符串s3=swap(str,p2.getKey(),p2.getValue());
添加(s3);
字符串s4=交换(s3,p1.getKey(),p1.getValue());
添加(s4);
返回set.last();
}
专用静态字符串交换(字符串str、int a、int b){
StringBuilder sb=新的StringBuilder(str);
char temp1=str.charAt(a);
char temp2=str.charAt(b);
b.塞查拉特(a、temp2);
b.塞查拉特(b,temp1);
使某人返回字符串();
}
这里是我的Java解决方案:
String swapLexOrder(String str, int[][] pairs) {
Map<Integer, Set<Integer>> neighbours = new HashMap<>();
for (int[] pair : pairs) {
// It contains all the positions that are reachable from the index present in the pairs
Set<Integer> reachablePositionsL = neighbours.get(pair[0]);
Set<Integer> temp = neighbours.get(pair[1]); // We use it just to merge the two sets if present
if (reachablePositionsL == null) {
reachablePositionsL = (temp == null ? new TreeSet<>() : temp);
} else if (temp != null) {
// Changing the reference so every addition to "reachablePositionsL" will reflect on both positions
for (Integer index: temp) {
neighbours.put(index, reachablePositionsL);
}
reachablePositionsL.addAll(temp);
}
reachablePositionsL.add(pair[0]);
reachablePositionsL.add(pair[1]);
neighbours.put(pair[0], reachablePositionsL);
neighbours.put(pair[1], reachablePositionsL);
}
StringBuilder result = new StringBuilder(str);
for (Set<Integer> set : neighbours.values()) {
Iterator<Character> orderedCharacters = set.stream()
.map(i -> str.charAt(i - 1))
.sorted(Comparator.reverseOrder())
.iterator();
set.forEach(i -> result.setCharAt(i - 1, orderedCharacters.next()));
}
return result.toString();
}
字符串交换顺序(字符串str,int[][]对){
Map neights=newhashmap();
for(int[]对:对){
//它包含从成对中存在的索引可以到达的所有位置
设置reachablePositionsL=neights.get(对[0]);
Set temp=neights.get(pair[1]);//我们使用它只是合并两个集合(如果存在)
if(reachablePositionsL==null){
可达位置sl=(temp==null?新树集():temp);
}否则如果(温度!=null){
//更改参考,以便每次添加“可达位置SL”都会反映两个位置
用于(整数索引:temp){
放置(索引,可到达位置SL);
}
可到达位置SL.addAll(温度);
}
可达位置sl.add(对[0]);
可达位置SL.add(对[1]);
put(对[0],可达位置sl);
put(对[1],可达位置sl);
}
StringBuilder结果=新的StringBuilder(str);
for(Set:neights.values()){
迭代器orderedCharacters=set.stream()
.map(i->str.charAt(i-1))
.sorted(Comparator.reverseOrder())
.iterator();
set.forEach(i->result.setCharAt(i-1,orderedCharacters.next());
}
返回result.toString();
}
一篇解释我的问题的文章。你的论点是什么?只需将字符串按降序排序,就像它是一个数组一样numbers@LibertyPaul:这不符合要求。给定一个字符串
“abcd”
和一对索引(3,4)
,您只能获得“abcd”
和“abdc”
。好的,那么mystring[1]对应的字符不应该是b,mystring[4]不应该是indexootfound
@Zeus我假设它们从1开始索引(像Matlab)而不是从0开始索引(像Python)。所以mystring[1]
应该是'a'
,而mystring[4]
应该是'c'
。
String = "abcd"
co_ord = [(1,4),(3,4)]
def find_combinations(co_ord, String):
l1 = []
for tup_le in co_ord:
l1.extend(tup_le)
l1 = [x-1 for x in l1]
l1 = list(set(l1))
l2 = set(range(len(String)))-set(l1)
return l1,int(''.join(str(i) for i in l2))
def perm1(lst):
if len(lst) == 0:
return []
elif len(lst) == 1:
return [lst]
else:
l = []
for i in range(len(lst)):
x = lst[i]
xs = lst[:i] + lst[i+1:]
for p in perm1(xs):
l.append([x]+p)
return l
lx, ly = find_combinations(co_ord, String)
final = perm1(lx)
print(final)
temp = []
final_list=[]
for i in final:
for j in i:
temp.append(String[j])
final_list.append(''.join(temp))
temp=[]
final_list = [ i[:ly] + String[ly] + i[ly:] for i in final_list]
print(sorted(final_list,reverse=True)[0])
String swapLexOrder(String str, int[][] pairs) {
Map<Integer, Set<Integer>> neighbours = new HashMap<>();
for (int[] pair : pairs) {
// It contains all the positions that are reachable from the index present in the pairs
Set<Integer> reachablePositionsL = neighbours.get(pair[0]);
Set<Integer> temp = neighbours.get(pair[1]); // We use it just to merge the two sets if present
if (reachablePositionsL == null) {
reachablePositionsL = (temp == null ? new TreeSet<>() : temp);
} else if (temp != null) {
// Changing the reference so every addition to "reachablePositionsL" will reflect on both positions
for (Integer index: temp) {
neighbours.put(index, reachablePositionsL);
}
reachablePositionsL.addAll(temp);
}
reachablePositionsL.add(pair[0]);
reachablePositionsL.add(pair[1]);
neighbours.put(pair[0], reachablePositionsL);
neighbours.put(pair[1], reachablePositionsL);
}
StringBuilder result = new StringBuilder(str);
for (Set<Integer> set : neighbours.values()) {
Iterator<Character> orderedCharacters = set.stream()
.map(i -> str.charAt(i - 1))
.sorted(Comparator.reverseOrder())
.iterator();
set.forEach(i -> result.setCharAt(i - 1, orderedCharacters.next()));
}
return result.toString();
}