leetcode:1754.构造字典序最大的合并字符串【贪心】-创新互联
目录
网页名称:leetcode:1754.构造字典序最大的合并字符串【贪心】-创新互联
分享链接:http://scyanting.com/article/ddecog.html
- 题目截图
- 题目分析
- java
- python
- 总结
- 简单地比较当前位置不行!
- 要看后面所有的substring哪个更大,就选哪个!
- 因为这样才可以引导指针走向较大的一方!
class Solution {public String largestMerge(String word1, String word2) {StringBuilder sb = new StringBuilder();
int i = 0, j = 0;
while (i< word1.length() || j< word2.length()) {if (i< word1.length() && word1.substring(i).compareTo(word2.substring(j)) >0) {sb.append(word1.charAt(i));
++i;
} else {sb.append(word2.charAt(j));
++j;
}
}
return sb.toString();
}
}
pythonclass Solution:
def largestMerge(self, word1: str, word2: str) ->str:
# 贪心!
merge = ''
i, j, m, n = 0, 0, len(word1), len(word2)
while i< m or j< n:
# 表明沿着这个方向效益大!
if word1[i:] >word2[j:]:
merge += word1[i]
i += 1
else:
merge += word2[j]
j += 1
return merge
总结- 千奇百怪的贪心。。。
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧
网页名称:leetcode:1754.构造字典序最大的合并字符串【贪心】-创新互联
分享链接:http://scyanting.com/article/ddecog.html