POJ3617 Best Cow Line
来源:互联网 发布:网络是一把双刃剑 编辑:程序博客网 时间:2024/06/01 09:00
题意:给出一个字符串s,每次从字符串s首部或者尾部取一个字符,拼成新的字符,使得字典序最小。
思路:使用贪心算法 。
(1)如果首部字符小于尾部字符,取首部字符
(2)如果首部字符大于尾部字符,取尾部字符
(3)如果首部字符等于尾部字符,取首部或者尾部都可以
代码如下:
import java.io.*;import java.util.Scanner;class Solution{ public static String solve(String s) { int start = 0, end = s.length() - 1; StringBuilder sb = new StringBuilder(); while (start <= end) { boolean left = false; for (int i = 0; i + start <= end; i++) { if (s.charAt(start + i) < s.charAt(end - i)) { left = true; break; } else if (s.charAt(start + i) > s.charAt(end - i)) { left = false; break; } } if (left) { sb.append(s.charAt(start++)); } else { sb.append(s.charAt(end--)); } } return sb.toString(); }}class MySystem{ private static Scanner cin; private static PrintWriter cout; private final static boolean DEBUG = false; private MySystem(){} static { init(); } private static void init() { try { if (DEBUG) { cin = new Scanner(new BufferedInputStream(new FileInputStream("d:\\program\\intelj\\spoj\\src\\spoj.txt"))); } else { cin = new Scanner(new BufferedInputStream(System.in)); } cout = new PrintWriter(new BufferedOutputStream(System.out)); } catch (IOException e) { e.printStackTrace(); } } public static Scanner getInput() { return cin; } public static PrintWriter getOutput() { return cout; }}public class Main { public static void main(String[] args) { Scanner cin = MySystem.getInput(); PrintWriter cout = MySystem.getOutput(); while (cin.hasNext()) { int n = cin.nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append(cin.next()); } String ans = Solution.solve(sb.toString()); int limit = 80; int lines = (ans.length() + limit - 1)/ limit; for (int i = 0; i < lines; i++) { if (i != lines - 1) cout.println(ans.substring(i * limit, (i + 1) * limit)); else cout.print(ans.substring(i * limit)); } cout.flush(); } }}
0 0
- POJ3617 Best Cow Line
- POJ3617 Best Cow Line
- POJ3617 Best Cow Line
- best cow line(poj3617)
- POJ3617-Best Cow Line
- POJ3617 Best Cow Line
- POJ3617 Best Cow Line
- poj3617 Best Cow Line
- POJ3617 Best Cow Line
- POJ3617-Best Cow Line
- poj3617 Best Cow Line
- poj3617 Best Cow Line
- POJ3617 Best Cow Line
- POJ3617 Best Cow Line
- poj3617 Best Cow Line 贪心
- POJ3617 Best Cow Line 贪心
- poj3617 Best Cow Line 贪心
- poj3617 Best Cow Line 贪心
- python scrapy 下载文件与图片相关小知识
- org.springframework.dao.InvalidDataAccessApiUsageException问题解决与分析
- 异常
- QT5.8 VS2015生成兼容xp系统的可执行程序
- pico-ctf-2013 overflow-3
- POJ3617 Best Cow Line
- 基础练习 分解质因数
- Bootstrap之表格,按钮,表单和图片的样式
- 8086汇编学习之标志位寄存器的应用
- 前Vue,后Express的'Access-Control-Allow-Origin'问题
- 机器学习实战-第五章(logistic回归)
- 历届试题 蚂蚁感冒
- Java实现 Windows Socket TCP实现大文件的传输
- ZOJ3936-Apples and Ideas