题目
Take 2 strings s1 and s2 including only letters from ato z. Return a new sorted string, the longest possible, containing distinct letters,
each taken only once – coming from s1 or s2.
Examples
a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"
a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"
代码
using System;
using System.Linq;
public class TwoToOne
{
public static string Longest (string s1, string s2)
{
string ss="";
var ordered1=s1.OrderBy(c=>c);
var ordered2=s2.OrderBy(c=>c);
string ns1=new string(ordered1.ToArray());
string ns2=new string(ordered2.ToArray());
//s1或s2等于空的情况
if(ns1==""){
foreach(char c in s2){
if(!ss.Contains(c)){ss+=c;}
}
return ss;
}
if(ns2==""){
foreach(char c in s1){
if(!ss.Contains(c)){ss+=c;}
return ss;
}
}
//s1、s2不为空
for(int i=0;i<ns1.Length;i++){
char c1=ns1[i];
if(!ss.Contains(c1)){ss+=c1;}
}
for(int i=0;i<ns2.Length;i++){
char c2=ns2[i];
if(!ss.Contains(c2)){ss+=c2;}
}
var ordered3=ss.OrderBy(c=>c);
string output=new string(ordered3.ToArray());
return output;
}
}
(别人的)简洁写法
Linq真的很方便,然而我用得还不够熟练。
using System.Linq;
public class TwoToOne
{
public static string Longest (string s1, string s2)
{
return new string ((s1 +s2).Distinct().OrderBy(x=>x).ToArray ());
}
}
参考资料
- Enumerable.Distinct Method
https://docs.microsoft.com/zh-cn/dotnet/api/system.linq.enumerable.distinct?view=netframework-4.8
提供一组用于查询实现 IEnumerable的对象的 static 方法。