算法刷题(一)1153.字符串排序(LintCode算法题)

算法刷题(一)1153.字符串排序

题目来源LintCode算法

1.描述

给定一些由,隔开的字符串,请将他们按字典序排列。

2.要求

  • 字符串仅包含小写字母。
  • 字符串数量≤1000且总长度≤10e5

3.样例

样例 1

输入: "bb,aa,lintcode,c"
输出: "aa,bb,c,lintcode"
说明: 在字典序中,"aa" < "bb" < "c" < "lintcode"

挑战

你可以自己写一个排序函数吗?

4.思考

  • ,隔开的字符串,要排序,可以将其利用split()分割为字符串数组
  • 按字典序排序小写字母,String提供了compareTo比较两个字符串的字典大小
  • 然后就是排序方法

方法

public class Solution {
    /**
     * @param s: string
     * @return: sort string in lexicographical order
     */
    public String sorting(String s) {
        // write your code here
        String[] sarray = s.split(",");
        StringBuilder news = new StringBuilder();
        TwoTree tt = new TwoTree();
        
        for (int i=0;i<sarray.length;i++ ) {
            tt.addTree(sarray[i]);
        } 
        List<String> sl = tt.sort();
        for (int i=0;i<sl.size();i++ ) {
            if(i == sl.size()-1) {
                news.append(sl.get(i));
                break;
            }
            news.append(sl.get(i)+",");
        } 
        return news.toString();
        
    }
  //内部类,二叉树排序
	public class TwoTree {
		public String node;//中心节点
		public TwoTree leftnode;//左子树
		public TwoTree rightnode;//右子树
	
		public  void addTree(String v) {
			//判断中心节点是否为空
			if(node == null) {
				node = v;
			}else {
				//判断节点与v的字典关系,小进左子树
				if(v.compareTo(node) <= 0) {
					if(leftnode == null) {
						leftnode = new TwoTree();
					}
					leftnode.addTree(v);
				}
				//大进右子树
				if(v.compareTo(node) > 0) {
					if(rightnode == null) {
						rightnode = new TwoTree();
					}
					rightnode.addTree(v);
				}
			}
		}
		//排序,从小到大,右子树放在上面就是从大到小
		public  List<String> sort(){
			List<String> sl = new ArrayList<String>();
      //左子树
			if(null != leftnode) {
				sl.addAll(leftnode.sort());
			}
			sl.add(node);
      //右子树
			if(null != rightnode) {
				sl.addAll(rightnode.sort());
			}		
			return sl;
		}
	}
}

5.参考答案

九章算法参考答案

6.总结

这道题其实,就是好的排序方式加上比较两个字符串,字符串的比较是可以用原生方法compareTo比较,排序方式好了,时间复杂度自然就降下来了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

这可怎么整啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值